I'm converting some java code to ColdFusion. I've figured out most of it except for this section:
String passKey = "D:\\tmp\\passbook\\key\\pass.p12";
String password = "";
String appleFile = "D:\\tmp\\passbook\\key\\AppleWWDRCA.pem";
String pathToTemplateDirectory = "D:/tmp/passbook/t";
PKSigningInformation pkSigningInformation =
PKSigningUtil.loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(passKey, password, appleFile);
byte[] passZipAsByteArray = PKSigningUtil.createSignedAndZippedPkPassArchive(pass, pathToTemplateDirectory, pkSigningInformation);
FileUtils.forceDelete(new File("D:\\workspace\\emms_maven\\src\\main\\webapp\\WEB-INF\\passbook\\new.pkpass"));
FileUtils.writeByteArrayToFile(new File("D:\\workspace\\emms_maven\\src\\main\\webapp\\WEB-INF\\passbook\\new.pkpass"),
passZipAsByteArray);
On these lines I'm stuck. Basically I'm looking for the equivalent of forceDelete & writeByteArrayToFile in ColdFusion. Any ideas?
FileUtils.forceDelete(new File("D:\\workspace\\emms_maven\\src\\main\\webapp\\WEB-INF\\passbook\\new.pkpass"));
FileUtils.writeByteArrayToFile(new File("D:\\workspace\\emms_maven\\src\\main\\webapp\\WEB-INF\\passbook\\new.pkpass"),
passZipAsByteArray);
Those two lines are just deleting a file, then writing binary to the same file. Since CF has functions to delete and write files, I just used its regular file functions:
<cfset passZipAsByteArray = {}>
<cfset passZipAsByteArray = PKSigningUtil.createSignedAndZippedPkPassArchive(
pass, pathToTemplateDirectory,
pkSigningInformation) />
<cffile action="write"
file="#pathToTemplateDirectory#/#createUUID()#.pkpass"
output="#passZipAsByteArray#">
Related
what's the equivalent fileoutputstream of java in dart?
Java code
file = new FileOutputStream(logFile, true);
byte[] input = "String".getBytes();
file.write(input);
java file output
String
Ive tried this in dart
Dart code
var file = File(logFile!.path).openWrite();
List input = "String".codeUnits;
file.write(input);
[String]
and every time I open the file again to append "String2" and "String3" to it, the output will be
[String][String2][String3]
as oppose to java's output
StringString3String3
to sum it up, is there a way to fix/workaround this?
why each array bytes written in dart will be a new array instead of append into an existing one?
You can achieve that by using File.writeAsString() and using FileMode.append.
Picking up your example, this would be:
var file = File(logFile!.path);
file.writeAsString("String", mode: FileMode.append);
did you try writeAsString() ?
import 'dart:io';
void main() async {
final filename = 'file.txt';
var file = await File(filename).writeAsString('some content');
// Do something with the file.
}
Problem
I am trying to encode file contents of doc/pdf extensions to Base64 string in Java.
The encoded string length almost doubles from the original(115k -> 230k).
Whereas encoding the same file contents in Python/PHP or any online tool only gives a third increase(115k -> 154k).
What causes this increase in size for Java and is there any way to get equivalent result as the other sources?
Code
import java.util.Base64;
...
//String content;
System.out.println(content.length());
String encodedStr = new String(Base64.getEncoder().encode(content.getBytes()));
System.out.println(encodedStr.length());
String urlEncodedStr = new String(Base64.getUrlEncoder().encode(content.getBytes()));
System.out.println(urlEncodedStr.length());
String mimieEncodedStr = new String(Base64.getMimeEncoder().encode(content.getBytes()));
System.out.println(mimieEncodedStr.length());
Output
For pdf file
115747
230816
230816
236890
For doc file
13685
26392
26392
27086
First, never use new String. Second, pass an encoding to String.getBytes(String) (e.g. content.getBytes(encoding)). For example,
String encodedStr = Base64.getEncoder()
.encodeToString(content.getBytes("UTF-8"));
or
String encodedStr = Base64.getEncoder()
.encodeToString(content.getBytes("US-ASCII"));
I have a .csv file that contains:
scenario, custom, master_data
1, ${CUSTOM}, A_1
I have a string:
a, b, c
and I want to replace 'custom' with 'a, b, c'. How can I do that and save to the existing .csv file?
Probably the easiest way is to read in one file and output to another file as you go, modifying it on a per-line basis
You could try something with tokenizers, this may not be completely correct for your output/input, but you can adapt it to your CSV file formatting
BufferedReader reader = new BufferedReader(new FileReader("input.csv"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"));
String custom = "custom";
String replace = "a, b, c";
for(String line = reader.readLine(); line != null; line = reader.readLine())
{
String output = "";
StringTokenizer tokenizer = new StringTokenizer(line, ",");
for(String token = tokenizer.nextToken(); tokenizer.hasMoreTokens(); token = tokenizer.nextToken())
if(token.equals(custom)
output = "," + replace;
else
output = "," + token;
}
readInventory.close();
If this is for a one off thing, it also has the benefit of not having to research regular expressions (which are quite powerful and useful, good to know, but maybe for a later date?)
Have a look at Can you recommend a Java library for reading (and possibly writing) CSV files?
And once the values have been read, search for strings / value that start with ${ and end with }. Use Java Regular Expressions like \$\{(\w)\}. Then use some map for looking up the found key, and the related value. Java Properties would be a good candidate.
Then write a new csv file.
Since your replacement string is quite unique you can do it quickly without complicated parsing by just reading your file into a buffer, and then converting that buffer into a string. Replace all occurrences of the text you wish to replace with your target text. Then convert the string to a buffer and write that back to the file...
Pattern.quote is required because your string is a regular expression. If you don't quote it you may run into unexpected results.
Also it's generally not smart to overwrite your source file. Best is to create a new file then delete the old and rename the new to the old. Any error halfway will then not delete all your data.
final Path yourPath = Paths.get("Your path");
byte[] buff = Files.readAllBytes(yourPath);
String s = new String(buff, Charset.defaultCharset());
s = s.replaceAll(Pattern.quote("${CUSTOM}"), "a, b, c");
Files.write(yourPath, s.getBytes());
Hey guy's so am trying to replace all characters and numbers to get the /hello/what/ only without the REMOVEThis4.PNG i don't want to use string.replace("REMOVEThis4.PNG", ""); cause i wanna use it on other strings not only that
Any help is great my code
String sFile = "/hello/what/REMOVEThis4.PNG";
if (sFile.contains("/")){
String Replaced = sFile.replaceAll("(?s)", "");
System.out.println(Replaced);
}
I want the the output to be
/hello/what/
Only thanks alot!
If you are trying to parse a path, I recommend to find the last index of /, and get the substring to this index plus one. So
string = string.substring(0, string.lastIndexOf("/") + 1);
No need to use regular expressions in your case:
String sFile = "/hello/what/REMOVEThis4.PNG";
// TODO check actual last index of "/" against -1
System.out.println(sFile.substring(0, sFile.lastIndexOf("/") + 1));
Output
/hello/what/
Note
In case you are dealing with actual files, you can probably spare yourself the String manipulation and use File.getParent() instead:
File file = new File("/hello/what/REMOVEThis4.PNG");
System.out.println(file.getParent());
Output (may change depending on your system)
\hello\what
Use Java's File API:
String example = "/hello/what/REMOVEThis4.PNG";
File file = new File(example);
System.out.println(example);
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
System.out.println(filePath);
Lets say I have a URL http://example.com/files/public_files/test.zip and I want to extract the last subpath so test.zip, How would I be able do this?
I am from Python so I am still new to Java and learning. In Python you could do something like this:
>>> x = "http://example.com/files/public_files/test.zip"
>>> x.split("/")[-1]
'test.zip'
There are many ways. I prefer:
String url = "http://example.com/files/public_files/test.zip";
String fileName = url.substring(url.lastIndexOf("/") + 1);
Using String class method is a way to go. But given that you are having a URL, you can use java.net.URL.getFile():
String url = "http://example.com/files/public_files/test.zip";
String filePart = new URL(url).getFile();
The above code will get you complete path. To get the file name, you can make use of Apache Commons - FilenameUtils.getName():
String url = "http://example.com/files/public_files/test.zip";
String fileName = FilenameUtils.getName(url);
Well, if you don't want to refer to 3rd party library for this task, String class is still an option to go for. I've just given another way.
you can use the following:
String url = "http://example.com/files/public_files/test.zip";
String arr[] = url.split("/");
String name = arr[arr.length - 1];
Most similar to the python syntax is :
String url = "http://example.com/files/public_files/test.zip";
String [] tokens = url.split("/");
String file = tokens[tokens.length-1];
Java lacks the convenient [-n] nth to last selector that Python has. If you wanted to do it all in one line, you'd have to do something gross like this:
String file = url.split("/")[url.split("/").length-1];
I don't recommend the latter