Use createNewFile() , which will atomize the file only if it does not already exist.
If the file is created, the name is valid and does not kill the existing file. Then you can open files and efficiently copy data from one to another using FileChannel.transferXXX operations.
It is important to remember that in general, verification and creation should be atomic. If you first check if the operation is safe, then perform the operation as a separate step, the conditions can be changed at the same time, which makes the operation unsafe.
Further information on food can be found in this related entry: "Move / Copy Operations in Java."
Update:
Following this answer, NIO.2 APIs were introduced that add more interaction to the file system.
Suppose you have an interactive program and want to check after each keystroke that the file is potentially valid. For example, you can enable the “Save” button only when the record is valid, and a dialog box with an error message after clicking “Save” does not appear. Creating and securing the removal of the large number of junk files that my suggestion above would require seems like a mess.
With NIO.2, you cannot create a Path instance containing characters that are illegal for the file system. InvalidPathException is InvalidPathException as soon as you try to create a Path .
However, the API does not check illegal names consisting of valid characters, such as "PRN" on Windows. As a workaround, experimentation showed that using an invalid file name would throw a separate exception when trying to access attributes (for example, using Files.getLastModifiedTime() ).
If you provide a legal name for a file that exists, you will not receive any exception.
If you specify a legal name for a file that does not exist, it raises a NoSuchFileException .
If you specify an illegal name, a FileSystemException will be raised.
However, this seems very kludgey and can be unreliable on other operating systems.