Java File Handling

Java File Handling

Java provides several classes and methods to handle file operations. The java.io package contains classes for file input and output. The most common classes used are File, FileReader, FileWriter, BufferedReader, and BufferedWriter.

Writing to a File

import java.io.FileWriter;
import java.io.IOException;

public class FileHandlingExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, Java File Handling!");
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

This example shows how to write to a file using the FileWriter class. It writes the string "Hello, Java File Handling!" to a file named "example.txt".

Reading from a File
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class FileHandlingExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

In this example, the BufferedReader class is used to read the contents of the "example.txt" file line by line and print it to the console.

Creating a New File

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

public class FileHandlingExample {
    public static void main(String[] args) {
        try {
            File file = new File("newfile.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

The File class provides the createNewFile() method to create a new file. This method returns true if the file was successfully created, or false if it already exists.

Deleting a File

import java.io.File;

public class FileHandlingExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.delete()) {
            System.out.println("File deleted: " + file.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}
    

To delete a file, the File class provides the delete() method. This method returns true if the file was successfully deleted, or false otherwise.