Java Create File Example

In this source code example, we show you how to create a file in Java.

We use Files.createFile() method to create a file in Java.

Files.createFile() 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 Create File Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.HashSet;
import java.util.Set;

public class JavaCreateFile {

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

        Set<PosixFilePermission> perms = new HashSet<>();

        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);
        perms.add(PosixFilePermission.OTHERS_READ);

        FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);

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

        if (Files.exists(myPath)) {
            
            System.out.println("File already exists");
        } else {
            
            Files.createFile(myPath, attrs);
            System.out.println("File created");
        }
    }
}
Create a new file named "sample.txt" if the file does not exist:
        if (Files.exists(myPath)) {
            
            System.out.println("File already exists");
        } else {
            
            Files.createFile(myPath, attrs);
            System.out.println("File created");
        }

References


Comments