Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gaining control on the name of the temp file created in Java

Tags:

java

file

Is there any way to control the random digits appended to a file name when a tempFile is created ? For eg. if I write File.createTempFile("abc",".pdf"), it creates a file with name abc12323543121.pdf. Instead of these digits, is it possible to append a timestamp ? I need this because for every file that i create, I need to append the timestamp to the file, which makes the file name quite long. So, instead of the randomly generated digits,if I could just use the timestamp, it would be really great.

like image 342
Adarsh Avatar asked May 22 '13 07:05

Adarsh


1 Answers

It seems that the API does not directly provide this. But you can have a look into the File.createTempFile() source code to see how it is implemented, and then implement the required method yourself.

Basically, createTempFile() creates a File object with the intended file name, and then uses FileSystem.createFileExclusively() to create the file. This method returns false if the file already exists, in which case the file name is modified (by using a different random number) and the creation is retried.

You can follow the same approach, but note that FileSystem is a package private class, hence you can not use it in your own method. Use File.createNewFile() instead to create the file atomically. This method also returns false in case the file already exists, so you can use it in a similar loop like createTempFile() uses the createFileExclusively() method.

like image 113
Andreas Fester Avatar answered Oct 11 '22 07:10

Andreas Fester