How to Read and Write Files in Java Using FileReader and FileWriter

I explored how to perform basic file handling in Java using FileReader and FileWriter. This article explains both reading and writing operations step-by-step with code examples and output.

 

-Introduction
– Writing to a File using FileWriter
– Reading from a File using FileReader
– Conclusion
– Note

 

File handling is an essential part of programming.
In Java, we can use the `FileReader` class to read from a file and `FileWriter`
class to write into a file. These classes are part of `java.io` package.

Writing to a File using FileWriter

The `FileWriter` class allows us to write character data to a file. If the file doesn’t exist, it will be created automatically.

Code–

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

public class WriteToFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("Hello, this content is written using FileWriter in Java.");
            writer.close();
            System.out.println("Data successfully written to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
OUTPUT(in console):
Data successfully written to the file.
File content (output.txt):
Hello, this content is written using FileWriter in Java.

Reading from a File using FileReader

The FileReader class is used to read data from a file character by character.

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

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

Output (in console):

csharp
Hello, this content is written using FileWriter in Java.

Note:

Make sure the file output.txt exists in the project root directory when you try to read it. Otherwise, Java will throw a FileNotFoundException.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top