File Handling in Java

File handling in Java refers to reading from or writing to a file in a Java program. Here are the discription of some common Java classes used for file handling.

  • File class in Java represents a file or directory in the file system. It provides methods to perform various file-related operations such as creating a new file, deleting a file, checking if a file exists, etc.

  • FileWriter class in Java provides a convenient way to write characters to a file. It allows you to write text to a file, either by overwriting existing contents or appending to the end of the file.

  • FileReader class in Java provides a convenient way to read characters from a file. It allows you to read the contents of a file, one character at a time.

Here's a tutorial on how to perform file handling in Java.

Opening a file

The first step in file handling is to open a file. This can be done using the File class and its associated methods. To open a file, you need to create a File object and pass the file path as a parameter to its constructor. For example:

File file = new File("file.txt");

Reading from a file

After opening the file, you can read its contents using the FileReader class and its associated methods. To read from a file, you need to create a FileReader object and pass the File object as a parameter to its constructor. For example:

FileReader fr = new FileReader(file);
int c = fr.read();
while (c != -1) {
  System.out.print((char) c);
  c = fr.read();
}
fr.close();

Writing to a file

You can write to a file using the FileWriter class and its associated methods. To write to a file, you need to create a FileWriter object and pass the File object as a parameter to its constructor. For example:

FileWriter fw = new FileWriter(file);
fw.write("Hello World!");
fw.close();

Closing a file

After reading from or writing to a file, it is important to close the file to free up system resources. This can be done using the close method on the FileReader or FileWriter object.

Java program to demonstrate file handling

import java.io.*;

public class FileHandling {
    public static void main(String[] args) throws IOException {
        File file = new File("file.txt");

        // Write to file
        FileWriter fw = new FileWriter(file);
        fw.write("Hello World!");
        fw.close();

        // Read from file
        FileReader fr = new FileReader(file);
        int c = fr.read();
        while (c != -1) {
            System.out.print((char) c);
            c = fr.read();
        }
        fr.close();
    }
}
Output
Hello World!

This program will create a file named file.txt and write "Hello World!" to it. Then, it will read the contents of the file and print it to the console.