How can I create a new file in Java?

To create a new file in Java, you can use the File class along with the createNewFile() method.

Following is an example:

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

public class CreateFileDemo {
    public static void main(String[] args) {
        // Specify the path and name of the file
        String filePath = "C:\\path\\to\\your\\directory\\example.txt";

        try {
            // Create a File object
            File file = new File(filePath);

            // Check if the file doesn't exist, then create it
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Replace the filePath with the desired location and name of your file. This code checks if the file already exists.

If the file is already there in the location then it will print following output in the console:

File already exists.

If it doesn’t then creates a new file.

Make sure to handle IOException appropriately in a real-world scenario.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments