In this quick article, you'll learn how to create a new file in Java using both legacy I/O API as well as new I/O API (NIO). In the end, we'll also look at a 3rd party — Apache Commons IO that can also be used to create a new file in Java.

Using Files.createFile() Method

In Java 7 and higher, you can use the Files.createFile() static method to create a new and empty file. This method accepts a Path object as a parameter to create a new file. Here is an example:

try {
    // create a new file
    Path path = Files.createFile(Paths.get("file.txt"));

    // print absolute file path
    System.out.println(path.toAbsolutePath().toString());

} catch (IOException ex) {
    ex.printStackTrace();
}

As you can see above, the code is very simple and clean. Files.createFile() creates a new file and returns the path as a Path object. If a file with the same name already exists, a FileAlreadyExistsException exception is thrown.

Using File.createNewFile() Method

Another way to create a new file in Java is by using the legacy File.createNewFile() method (available since JDK 1.2). This method returns a boolean value (true) if the file is created successfully. If there is an error or the file already exists, it returns false.

Here is an example:

try {
    // create a file instance
    File file = new File("file.txt");

    // create new file
    if (file.createNewFile()) {
        System.out.println("File is created successfully!");
    } else {
        System.out.println("File already exists.");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}

Using Apache Commons IO

The Apache Commons IO library provides FileUtils.touch() to create a new file in Java. This method implements the exact same behavior as the touch command on Unix. It creates a new empty file in the file system including creates parent directories if they do not exist. If the file already exists, it is opened and closed without modifying it, but updating the file date and time.

Here is an example:

try {
    // create a new empty file
     FileUtils.touch(new File("file.txt"));

} catch (IOException ex) {
    ex.printStackTrace();
}

Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

For a Gradle project, add the following dependency to your build.gralde file:

implementation 'commons-io:commons-io:2.6'

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.