Skip to content

Java Creating file with File.createNewFile() Method

Ramesh Fadatare edited this page Jul 11, 2019 · 1 revision

The Java File's createNewFile() method creates a new, empty file named by the pathname if a file with this name does not yet exist.

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

public class JavaCreateFileEx {

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

        File file = new File("src/main/resources/myfile.txt");

        if (file.createNewFile()) {
            
            System.out.println("File has been created.");
        } else {
        
            System.out.println("File already exists.");
        }
    }
}

Output:

File has been created.

The createNewFile() returns true if the named file does not exist and was successfully created; false if the named file already exists.

Clone this wiki locally