Create New Files in Java

Tags: Java File Java IO Java NIO

Introduction

In this article we learn how to create a new file in a Java application by using core Java classes of IO and NIO packages.

Using Java NIO Files.createFile() static method

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

public class FilesCreateFileExample {
    public static void main(String... args) {
        try {
            String fileName = "D:\\Files\\test.txt";
            Path filePath = Paths.get(fileName);
            
            Path createdFile = Files.createFile(filePath);

            System.out.println("New file created at: " + createdFile.toAbsolutePath().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:
New file created at: D:\Files\test.txt

The Files.createFile() static method will throw an exception in case the file already existed.

Output:

java.nio.file.FileAlreadyExistsException: D:\Files\test.txt
	at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:81)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
	at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
	at java.nio.file.Files.newByteChannel(Files.java:361)
	at java.nio.file.Files.createFile(Files.java:632)
	at FilesCreateFileExample.main(FilesCreateFileExample.java:12)

Using Java IO File.createNewFile() method

With File.createNewFile() method, it will return a boolean value true if the new file created otherwise it returns false. In case the file already existed we will get the false value.

import java.io.File;
import java.io.IOException;

public class FileCreateNewFileExample {
    public static void main(String[] args) {
        try {
            String fileName = "D:\\Files\\test2.txt";

            File file = new File(fileName);
            boolean isCreated = file.createNewFile();

            System.out.println("New file create? " + isCreated);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:
New file create? true

Happy Coding 😊

Get File Size in Java

Get Absolute File Path of a File in Java

Write Text to a File in Java

Check Hidden Files in Java