Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean Java 7 way to create file if not exists [closed]

Tags:

java

file-io

nio

What is the Java 7 or Java 8 way to create a file if that does not exists?

like image 813
emotionull Avatar asked Jan 10 '15 15:01

emotionull


People also ask

How do you create a file in Java if it does not exist?

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.

How do I create a .java file?

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.

How do I override an existing file in Java?

To overwrite a file in Java, set the second argument of FileWriter to false .

What is Java NIO files?

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.


1 Answers

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.

like image 151
fge Avatar answered Sep 19 '22 16:09

fge