Read and Write Files in Java Using FileReader and FileWriter

Reading and writing files are essential operations in Java for dealing with data efficiently. File handling is one of the key components of Java programming, particularly when it comes to data storage and retrieval. Among Java’s various classes for reading from and writing to files, FileReader and FileWriter are straightforward yet efficient choices for working with character-based files. In this tutorial, we will explore how to use FileReader and FileWriter in Java, with clear examples and best practices.

 What are FileReader and FileWriter?

FileWriter:
  • It is used to write character-based data to the files.
  • Used to write a single string or character to a file.
  • By default, it overwrites files, but it can append to them if necessary.
FileReader:
  • It is used to read character-based files.
  • Reads information either line by line or character by character (when using BufferedReader).
  • It functions well with text files, but not binary files like PDFs or pictures.

Writing to a File Using FileWriter

 Example: Writing to a non-existing File

package FileHandling;

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

public class FileWriteExample {

    public static void main(String[] args) {
        String filepath = "Output.txt";
        String content1 = "This is an example of writing Strings to a file.";
       try( FileWriter writer = new FileWriter(filePath)){
            writer.write(content1);
       } catch (IOException e) {
           System.out.println("Error Found: " + e);
       }
    }
}

Output:

This is an example of writing Strings to a file.

Explanation:

  • A try-with-resources block is used to initialize FileWriter, ensuring that it will automatically close once the operation is complete. Additionally, if the file does not already exist, Java will automatically create it.
    try( FileWriter writer = new FileWriter(filePath))
  • write() method writes text to the file.
  • If an error occurs, such as a missing file or permission issues, the program catches the IOException and then prints a meaningful error message to inform the user.

Example: Appending to an existing file using FileWriter.

package FileHandling;

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

public class FileAppendExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("output.txt", true)) {
            writer.write("\nThis is an example of appending to a file.\n");
            System.out.println("Data appended successfully.");
        } catch (IOException e) {
            System.out.println("Error found: " + e.getMessage());
        }
    }
}

Output:

This is an example of writing Strings to a file.
This is an example of appending to a file.

Explanation:

FileWriter writer = new FileWriter("output.txt", true)

By default, FileWriter overwrites the existing content in a file. However, to preserve the previous data and append new content instead, you can use the FileWriter constructor with true as the second argument.

Reading a File Using FileReader

Example :

package FileHandling;

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

public class ReadFileExample {
    public static void main(String[] args) {
        try(FileReader r = new FileReader("output.txt")){
            int i ;
            while((i=r.read()) != -1){
                System.out.print((char)i);
            }
        }catch(IOException e){
            System.out.println("Error Found: "+ e);
        }
    }
}

Output:

This is an example of writing Strings to a file.
This is an example of appending to a file.

Explanation:

  • The read method processes the given text file and returns the ASCII value of characters present in it one by one. The loop iterates throughout the file using the read() method until it reaches -1 signaling the end of the file.
  • The obtained integer (ASCII) value is cast to a character before printing ensuring the original text is displayed in the output.

Java FileReader Class read() Method with Examples
To find the largest sentence in a .txt file using Java
Detect the number of pages in a PDF file using Java
To find the largest sentence in a .txt file using Java

 

Leave a Comment

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

Scroll to Top