There are various ways in which you can create a new file in Java. In this article, I’ve outlined the two most recommended way of creating new files.

Create New file using Java NIO (Recommended) - JDK 7+

You can use [Files.createFile(path)](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createFile(java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...)) method to create a new File in Java:

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 CreateNewFile {

    public static void main(String[] args)  {
        // New file path
        Path filePath = Paths.get("./bar.txt");

        try {
            // Create a file at the specified file path
            Files.createFile(filePath);
            System.out.println("File created successfully!");

        } catch (FileAlreadyExistsException e) {
            System.out.println("File already exists");
        } catch (IOException e) {
            System.out.println("An I/O error occurred: " + e.getMessage());
        } catch (SecurityException e) {
            System.out.println("No permission to create file: " + e.getMessage());
        }
    }
}

#java

How to create a new file in Java
1.55 GEEK