Java File Handling (File, FileReader, FileWriter): Read, Write and Manage Files Effectively

 Java File Handling (File, FileReader, FileWriter): Read, Write and Manage Files Effectively

File handling is an essential part of Java programming, especially when dealing with real-world applications such as data storage, configuration management, and log processing. Java provides a robust and flexible set of classes in the java.io package to handle file operations.

This blog post covers key classes involved in Java file handling:

  • File

  • FileReader

  • FileWriter


1. File Class

The File class in Java is used to represent file and directory pathnames in an abstract manner. It can be used for operations like creating new files/directories, checking file existence, deleting files, and more.

Key Methods of File Class:

  • createNewFile() – Creates a new file

  • exists() – Checks if a file or directory exists

  • delete() – Deletes the file or directory

  • getName() – Returns the name of the file

  • getAbsolutePath() – Returns the absolute pathname

  • length() – Returns the length of the file in bytes

Example:

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

public class FileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        try {
            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();
        }
    }
}

2. FileWriter Class

The FileWriter class is used to write character data to a file. It is a subclass of OutputStreamWriter and provides simple methods to write text to files.

Key Constructors and Methods:

  • FileWriter(String fileName) – Creates a writer that writes to the specified file

  • write(String str) – Writes a string to the file

  • write(char[] cbuf) – Writes an array of characters

  • append(char c) – Appends a single character

  • close() – Closes the writer stream

Example:

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

public class FileWriterExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, this is written using FileWriter.\n");
            writer.write("Java file handling is powerful!\n");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to file.");
            e.printStackTrace();
        }
    }
}

3. FileReader Class

The FileReader class is used to read character files. It is useful for reading text data and complements the FileWriter class.

Key Constructors and Methods:

  • FileReader(String fileName) – Creates a reader for the specified file

  • read() – Reads a single character

  • read(char[] cbuf) – Reads characters into an array

  • close() – Closes the stream

Example:

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("example.txt");
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Handling Exceptions and Best Practices

  1. Always close file streams to release system resources.

  2. Use try-with-resources (Java 7+) to automatically close streams.

  3. Check for file existence before reading.

  4. Handle IOException properly to avoid application crashes.

Try-With-Resources Example:

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

public class TryWithResourcesExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("sample.txt");
             FileReader reader = new FileReader("sample.txt")) {

            writer.write("Using try-with-resources in Java\n");

            int c;
            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Conclusion

Java's file handling capabilities using File, FileReader, and FileWriter provide a foundation for reading and writing files efficiently. By combining them with robust error handling and best practices, developers can manage files securely and effectively in their applications.

In real-world projects, you may also consider using buffered classes (BufferedReader, BufferedWriter) for more efficient file operations. However, the basics begin here—with File, FileReader, and FileWriter.

Previous
Next Post »