Java Create File with Files.createFile() API

In this example, I show you how to create a new file with Files.createFile() API.

java.nio.file.Files.createFile() API

This method creates a new and empty file, failing if the file already exists. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.

Java Files.createFile() Example

package net.javaguides.corejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaCreateFile {

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

        Path myPath = Paths.get("src/myfile.txt");

        if (Files.exists(myPath)) {
            System.out.println("File already exists");
        } else {
            Files.createFile(myPath);
            System.out.println("File created");
        }
    }
}
Output:
File created
In the above program, we get the Path of the file using Paths.get() method:
Path myPath = Paths.get("src/resources/myfile.txt");
Before we create the file, we check if it does not exist with Files.exists(). A FileAlreadyExistsException is thrown if we try to create an existing file.
if (Files.exists(myPath)) {
}
A file is created with Files.createFile(). It takes a Path of the file and a list of file attributes as parameters:
Files.createFile(myPath, attrs);

Reference

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html


Comments