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