I have a Java method that takes byte array and String value as arguments and returns a File object. This is the code
public File createTempFile(byte[] byteArray, String fileName) throws IOException {
String prefix = FilenameUtils.getBaseName(fileName);
String suffix = getMimeType(byteArray);
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fos.write(byteArray);
fos.close();
return tempFile;
}
When I try to run it like this
File myFile = tiedostoService.createTempFile(tiedosto.getContent(), attachment.getFileName());
I get an IOException like this
java.io.IOException: Unable to create temporary file, C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
at java.io.File$TempDirectory.generateFile(File.java:1921)
at java.io.File.createTempFile(File.java:2010)
From the stacktrace. it can be seen that it's trying to create a file like C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
and not C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image.png
How can I fix this? I'd really appreciate any sort of help.
'image/png' is a Mime Type. See all MimeTypes in java here
Write a util which converts mimetype to file extension. Hopefully this will help.
I think there is an extra \ in your suffix string, could you try debug and see the actual value of the suffix?
I tried to run:
String suffix = "\\png";
and got the same error, but if I do
String suffix = ".png";
no error creating the temp file, notice that you need to add a dot in the suffix...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With