I'am facing a weird issue in our dev domains . So basically our java app currently runs on jdk1.6 , we are planning to upgrade that to 1.8 . So currently the following code works fine in 1.6 but returns an exception
java.io.IOException: Unable to create temporary file, C:\Users\xxxxx\xxxxx\Local\Temp\XYZDirectory
at java.io.File$TempDirectory.generateFile(File.java:1921)
at java.io.File.createTempFile(File.java:2010)
at java.io.File.createTempFile(File.java:2070)
in 1.8 . Code is as follows -
File file = null;
try {
file =
File.createTempFile("XYZ", "Directory" + System.getProperty("file.separator"));
file.delete();
file.mkdirs();
} catch (final IOException e) {
e.printStackTrace();
}
return file;
We want our product to be compatible with both 1.6 and 1.8 .
After some research i found that i might have to use the following method of Files
class
public static Path createTempDirectory(Path dir,
String prefix,
FileAttribute<?>... attrs)
throws IOException
So i have the following queries -
1) Why File.createTempFile
throws an Exception in 1.8 ?
2) What is the conceptual difference between the two methods ?
3) More over if File.createTempFile
is no longer supported why it is not deprecated ?
4) What is the suitable way to address this issue ? In other words i can do a programmatic check to use appropriate method on the basis of jdk version installed in the VM and then proceed with the creation of temporary directory , but is this best way to to address this issue ?
This works on both:
File file = null;
try {
file = File.createTempFile("XYZ", "Directory");
file.delete();
file.mkdirs();
System.out.println(file);
} catch (final IOException e) {
e.printStackTrace();
}
return file;
I am not sure why concatenating the file separator fails, but that's the cause of the exception. My guess is that the separator is inserted programmatically by the File class and that you adding one manually causes the failure.
With that said, here is the NIO version introduced in Java 7 that is recommended:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class TempStackTest {
public Path getTempFilePath() {
Path path = null;
try {
path = Files.createTempFile("XYZ", "Directory");
path.toFile().delete();
} catch (final IOException e) {
e.printStackTrace();
}
return path;
}
}