Text Files in Java

1. Overview

In this article, we’ll look at different ways of writing into and reading from text files in Java. To learn how to read and write in binary files, we have the article Binary Files in Java.

2. Writing in Text File

We can write data in the text file using different implementations of the Writer class. The Writer class represents an abstract class for writing to character streams.

The following list shows the implementations of the Writer class:

  • CharArrayWriter,
  • FilterWriter,
  • BufferedWriter,
  • OutputStreamWriter,
  • PipedWriter,
  • PrintWriter,
  • StringWriter

However, we’ll not cover all the implementations in this article. Instead, we’ll focus on the most used ones. Each implementation provides the write() method which can be used to write data in the file.

2.1. FileWriter Class

Let’s see how can we use FileWriter class in order to write into text files.

The FileWriter class is used to write data represented by characters to the file. This class extends OutputStreamWriter class which extends the Writer class.

We’ll use FileWriter when we want to store a stream of characters in the file. For writing streams of bytes, we should consider using the FileOutputStream class instead. A detailed explanation of how to use it can be found in the article Binary Files in Java.

Let’s look at the example of how to write in the file using FileWriter class. Firstly, we’d need to create a new instance of the FileWriter class:

String filePath = "files/file_writer.txt"; 
FileWriter fileWriter = new FileWriter(filePath, true);

When creating a FileWriter instance, we need to pass the file path value. Additionally, we can pass a boolean value as a second argument. If the second argument is true, bytes will be written to the end of the file rather than the beginning. In other words, if true, we’ll append new values instead of writing over the existing ones.

The FileWriter will create a file instead of us if such a file is not already present.

Secondly, we’ll use the write() method in order to write characters in the file:

fileWriter.write("15646465464"); 
fileWriter.write(" "); 
fileWriter.write('j'); 
fileWriter.write(" "); 
fileWriter.write(String.valueOf(15)); 
fileWriter.write("\n");

We can pass char or String objects (including the char array).

2.2. BufferedWriter Class

The BufferedWriter class writes text to a character-output stream. Additionally, it buffers characters which provide us with an efficient way of writing single characters, arrays, and strings.

Now, let’s see how to write data in a file using BufferedWriter class. We’d need to pass an instance of a Writer as an argument when creating the BufferedWriter object. We can create an instance of the FileWriter class:

String filePath = "files/buffered_writer.txt"; 

FileWriter fileWriter = new FileWriter(filePath, true); 
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

Next, we can call its write() method and pass the String value:

bufferedWriter.write("ana-peterlic"); 
bufferedWriter.write(" "); 
bufferedWriter.write(String.valueOf(15)); 
bufferedWriter.newLine();

Moreover, the BufferedWriter class provides the newLine() method which will add a line separator in the file.

2.3. PrintWriter Class

The PrintWrtier class prints formatted representations of objects to the text-output stream. In other words, it will write a string representation of data in the file. 

The PrintWrtier class contains the print() method which can be used to write data in the file. Nevertheless, we can use the write() method for the String data as well.

Let’s write data in the file using PrintWrtier class:

String filePath = "java-core/files/dat/print_writer.txt";
try (FileWriter fileWriter = new FileWriter(filePath, true);
     PrintWriter printWriter = new PrintWriter(fileWriter))
{
    printWriter.write("test");
    printWriter.write("beenary");
    printWriter.print("value1");
} catch (Exception e)
{
    System.err.println("Error - " + e);
}

3. Reading From Text File

Likewise Writer class, Java provides the Reader class that is used for reading data from text files. It is an abstract class for reading character streams.

The following list shows the implementations of the Reader class:

  • BufferedReader,
  • CharArrayReader,
  • FilterReader,
  • InputStreamReader,
  • PipedReader,
  • StringReader

However, we’ll not cover all the implementations in this article. Instead, we’ll focus on the most used ones. Each implementation provides the read() method which can be used to read data from the file.

3.1. FileReader

The FileReader class is used for reading streams of characters from a file. For reading byte streams, we should consider using a FileOutputStream class instead.

Let’s see how to read characters from the file using the FileReader class.

Firstly, we need to create an instance of a FileReader class by providing a path to the file we want to read from:

String filePath = "files/order.txt";
FileReader fileReader = new FileReader(filePath);

Secondly, we need to create a loop that will execute until there are lines in the file:

int i;
while ((i = fileReader.read()) != -1) {
    System.out.println((char) i);
}

The read() method returns a single character or the -1 value if the end of the stream has been reached. Inside the while statement, we can perform actions with the read data.

3.2. BufferedReader

The BufferedReader class reads the text from a character-input stream. In addition, it buffers characters in order to provide an efficient reading of characters, arrays, and lines. We can think of BufferedReader as a class opposite from BufferedWriter class.

Now, let’s create an instance of the BufferedReader class:

String filePath = "files/order.txt";
BufferedReader br = new BufferedReader(new FileReader(filePath));

Using the while statement, we can get each line:

String row;
while ((row = br.readLine()) != null) {
    System.out.println(row);
}

4. Conclusion

In this tutorial, we’ve explained how data can be stored and read from textual files.

As always, the entire code of this example can be found over on GitHub.