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.
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.
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