Facebook PixelFile Creation | Java Tutorial | CodeWithHarry

File Creation

Java allows us to handle files and perform operations like create, read, write, update, and delete. This is known as File Handling in Java. The java.io package has all the classes you will require to perform input and output (I/O) in Java. For this tutorial, we will be using the File class from the java.io package.

A. Create a File:

The createNewFile() method is used to create new files in Java. This method throws an IOException if any error occurs. Hence, it is important to write it in a try...catch block.

Example:

import java.io.File;  
import java.io.IOException;
 
public class CreateFile {
    public static void main(String[] args) {
        try {
            File myObj = new File("students.txt");
            if (myObj.createNewFile()) {
                System.out.println("Created Successfully: " + myObj.getName());
            } else {
                System.out.println("Sorry, File Exists.");
            }
        } catch (IOException e) {
            System.out.println("Error.....");
            e.printStackTrace();
        }
    }
}

Output:

Created Successfully: students.txt

If we re-run the same code again, we get the following message:

Sorry, File Exists.