Gaining control over the name of a temporary file created in Java

Is there a way to control the random digits added to the file name when creating tempFile? E.g. if I write File.createTempFile("abc",".pdf") , it creates a file called abc12323543121.pdf . Can I add a timestamp instead of these numbers? I need this because for every file I create, I need to add a timestamp to the file, which makes the file name quite long. So, instead of randomly generated numbers, if I could just use a timestamp, that would be very cool.

+6
source share
2 answers

The API does not seem to directly provide this. But you can look at the source code of File.createTempFile() to find out how it is implemented, and then implement the required method yourself.

Basically, createTempFile() creates a File object with the name of the proposed file, 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 changed (using another random number), and the creation is repeated.

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

+7
source

You can create your own utility method for creating a temporary file. Mostly temporary files are stored in the temp directory as follows:

 public File createTempFile(String prefix, String suffix){ String tempDir = System.getProperty("java.io.tmpdir"); String fileName = (prefix != null ? prefix : "" ) + System.nanoTime() + (suffix != null ? suffix : "" ) ; return new File(tempDir, fileName); } 
+7
source

Source: https://habr.com/ru/post/945549/


All Articles