Java Create File with Files.createFile()

Java 7 introduced Files, which consists exclusively of static methods that operate on files, directories, or other types of files. The Files.createFile() method creates a new and empty file, failing if the file already exists.

Java Create File with Files.createFile()

The example creates a new, empty file with Files.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaCreateFileEx3 {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("src/main/resources/myfile.txt");

        try {
            Files.createFile(path);
            
        } catch (FileAlreadyExistsException ex) {
            
            System.err.println("File already exists");
        }
    }
}
A Path object is created. It is used to locate a file in a file system:
Path path = Paths.get("src/main/resources/myfile.txt");
The new file is created with Files.createFile():
Files.createFile(path);
FileAlreadyExistsException is thrown if the file already exists:
} catch (FileAlreadyExistsException ex) {

Comments