Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.
Creating a temporary fileThe File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.
Use File.createTempFile()
.
File tempFile = File.createTempFile("prefix-", "-suffix");
//File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();
Will create a file in the temp dir, like:
prefix-6340763779352094442-suffix
Since Java 7 there is the new file API "NIO2" which contains new methods for creating temnp files and directories. See
e.g.
Path tempDir = Files.createTempDirectory("tempfiles");
or
Path tempFile = Files.createTempFile("tempfiles", ".tmp");
Security notice:
Important difference between File.createTempFile()
and Files.createTempFile
is also that the latter has more secure permission defaults.
When no file attributes are specified, then the resulting file may have more restrictive access permissions to files created by the
File.createTempFile(String,String,File)
method.
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