Easy Tutorial
❮ Java Object Classes Java Basic Syntax ❯

Java Example - Creating a File

Java Examples

The following example demonstrates how to create a new file using the File() constructor of the File class and the file.createNewFile() method.

Main.java File

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

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("C:/myfile.txt");
            if (file.createNewFile())
                System.out.println("File created successfully!");
            else
                System.out.println("Error, the file already exists.");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

The above code outputs the following result when run:

File created successfully!

Java Examples

❮ Java Object Classes Java Basic Syntax ❯