What is the Java 7 or Java 8 way to create a file if that does not exists?
Java creating file with FileThe File's createNewFile method creates a new, empty file named by the pathname if a file with this name does not yet exist. The createNewFile returns true if the named file does not exist and was successfully created; false if the named file already exists.
Android Studio helps you to create new Java classes; enumeration and singleton classes; and interface and annotation types based on file templates. To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class.
To overwrite a file in Java, set the second argument of FileWriter to false .
The java. nio. file package defines classes to access files and file systems. The API to access file and file system attributes is defined in the java.
Not sure what you want, but for instance:
try {
Files.createFile(thePath);
} catch (FileAlreadyExistsException ignored) {
}
And there are other solutions; for instance:
if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS))
Files.createFile(thePath);
Note that unlike File
, these will throw exceptions if file creation fails! And relevant ones at that (for instance, AccessDeniedException
, ReadOnlyFileSystemException
, etc etc)
See here for more information. Also see why you should migrate to java.nio.file
, quickly.
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