Read and Write text files in Java



In Java, we have handy methods for handling text files - a crucial need in many applications. Whether you're managing data or saving information, knowing various Java approaches can make you a better programmer. Let's explore these methods with straightforward Java programs.

 

Introduction

Text files are a common part of Java applications. They help in reading data from a file or writing data to it in an organized way. Java provides different tools to make these operations smooth.

 

Methods for Reading Text Files

 

1. Using BufferedReader Class for Reading a Text File

One efficient method for reading a text file in Java is through the BufferedReader class. This class not only reads characters efficiently but also provides buffering capabilities, enhancing the speed of data retrieval. The buffer size can be specified or defaulted to a size sufficient for most purposes.

 

Example
import java.io.*;

public class ReadTextFileBufferedReader {
    public static void main(String[] args) throws Exception {

        // Specify the file path
        File file = new File("path/to/your/textfile.txt");

        // Create a BufferedReader object to efficiently read from the file
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            // Read each line from the file until the end is reached
            while ((line = br.readLine()) != null)
                System.out.println(line);

        }
    }
}
Output

If the content of "textfile.txt" is, for example:

Hello, BufferedReader!
This is a sample text file.

The output will be:

Hello, BufferedReader!

This is a sample text file.

 

Key Points
  • The BufferedReader efficiently reads text from the specified file path.
  • The readLine() method reads a line of text, and the process continues until the end of the file.
  • The buffered approach enhances performance by reducing the number of read requests made to the underlying stream.

 

2. Using Scanner Class for Reading and Writing a Text File

The Scanner class in Java provides a versatile approach for both reading and writing text files. It simplifies the process by breaking the input into tokens using a specified delimiter pattern. Let's explore an example that demonstrates both reading and writing line by line.

 

Example
import java.io.*;

public class ReadWriteTextFileUsingScanner {
    public static void main(String[] args) throws IOException {
        File file = new File("path/to/your/textfile.txt");

        System.out.println("Reading and Writing Line by Line");

        // Reading from the file using a Scanner
        try (Scanner sc = new Scanner(new FileReader(file))) {

            // Output each line until the end of the file using a loop
            while (sc.hasNextLine())
                System.out.println(sc.nextLine());
        }

        // Writing to the file using a FileWriter
        try (FileWriter writer = new FileWriter(file, true)) {

            // Appending a new line to the file
            writer.write("\nThis is a new line added through Java program.");
        }

        // Reading again to see the changes
        try (Scanner sc = new Scanner(new FileReader(file))) {

            System.out.println("\nAfter Writing:");

            // Output each line until the end of the file using a loop
            while (sc.hasNextLine())
                System.out.println(sc.nextLine());
        }
    }
}
Output

If the content of "textfile.txt" is initially:

Hello, Scanner!
This is another sample text file.

The output will be

Reading and Writing Line by Line
Hello, Scanner!
This is another sample text file.

After Writing:

Hello, Scanner!
This is another sample text file.
This is a new line added through the Java program.

 

Key Points
  • The Scanner class provides flexibility for both reading and writing text files, breaking input into tokens using a delimiter pattern.
  • This example demonstrates reading line by line using a loop and appending a new line to the file.

 

3. Using FileWriter Class for Writing a Text File

When it comes to writing content to a text file in Java, the FileWriter class provides a straightforward approach. This class allows you to append or overwrite text to an existing file or create a new file if it doesn't exist.

 

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

public class WriteTextFileFileWriter {
    public static void main(String[] args) throws IOException {

        String filePath = "path/to/your/textfile_written.txt";

        // Writing to the file using a FileWriter
        try (FileWriter writer = new FileWriter(filePath)) {

            // Writing content to the file
            writer.write("Hello, FileWriter!\n");
            writer.write("This is a new text file created through Java program.");

        }
        System.out.println("Content has been written to the file.");
    }
}
Output

If the content of "textfile_written.txt" is:

Hello, FileWriter!
This is a new text file created through Java program.

The program will print:

Content has been written to the file.

 

Key Points
  • The FileWriter class simplifies the process of writing text to a file.
  • The write() method allows you to add content to the file.
  • This example demonstrates creating a new file and writing content to it

 

4. Using Files.readAllLines and Files.write for Reading and Writing

Java provides convenient methods in the Files class for reading all lines from a file and writing content to a file. The readAllLines method reads all lines from a file and returns a List<String>. Similarly, the write method allows you to write a collection of strings to a file.

Example
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;

public class ReadWriteTextFileUsingFiles {
    public static void main(String[] args) throws IOException {

        String filePath = "path/to/your/textfile_files.txt";

        // Reading from the file using Files.readAllLines
        List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
        System.out.println("Reading from the file:");

        for (String line : lines) {
            System.out.println(line);
        }

        // Writing to the file using Files.write
        lines.add("This line is added through Java program using Files.write.");
        Files.write(Paths.get(filePath), lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

        System.out.println("\nAfter Writing:");

        // Reading again to see the changes
        lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);

        for (String line : lines) {
            System.out.println(line);
        }
    }
}
Output

If the content of "textfile_files.txt" is initially:

Hello, Files class!
This is another text file.

The output will be:

Reading from the file:

Hello, Files class!

This is another text file.

 

After Writing:

Hello, Files class!

This is another text file.

This line is added through Java program using Files.write.

 

Key Points
  • The Files class provides methods like readAllLines and write for efficient reading and writing operations.
  • The readAllLines method returns a List<String> containing all lines from the file.
  • The write method allows appending content to an existing file.


Thanks for feedback.



Read More....
Java Exception Handling
HashMap in Java
Java : HashSet and LinkedHashSet
Inner classes in Java
Java Collections Framework
Java Data Types and Variables - Declaration and Initialization