Java Program to Read Strings From a Text File

In this java program, we will learn different ways to read the contents of a text file as string. There are multiple ways by which we can read the contents of a file and convert them into a string in Java e.g. you can use Scanner, FileReader or BufferedReader class to read a text file as string.

Given a text file, the objective is to read the contents of a file in a current local directory and save it as a string. Consider a file on the system, say 'techcrashcourse.txt'. Here's the content of techcrashcourse.txt

This is a sample test file for demo.
It is a small txt file.

To understand this java program, you should have understanding of the following Java programming concepts:

Java Program to Check If String is Numeric using Parse Method

The read() method of the FileInputStream class is used to read the contents of a file. You must give a byte array as an argument to this method in order for the contents of the file to be read. To convert a byte array to Sting, provide the byte array as a parameter to the String class's constructor.

import java.io.File;
import java.io.FileInputStream;

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

    File file = new File("techcrashcourse.txt");
    FileInputStream fStream = new FileInputStream(file);

    byte[] byteArray = new byte[(int)file.length()];
    fStream.read(byteArray);

    String str = new String(byteArray);
    System.out.println(str);
  }
}
Output
This is a sample test file for demo.
It is a small txt file.

Java Program to Read a Text File as String using BufferedReader class

This was the traditional method of reading a file as a String in Java.  It reads the file line by line using the readLine() function and then joins them together using StringBuilder's append() method. Remember to attach the \n character to insert the line break; otherwise, all lines will be merged together and all content from the file will appear as a single long line.

import java.io.BufferedReader;
import java.io.FileReader;

public class ReadFileUsingBufferedReader {
  public static void main(String args[]) throws Exception {
    StringBuilder strBuiler = new StringBuilder();
    BufferedReader br = new BufferedReader(
    	new FileReader("techcrashcourse.txt"));
    String line = br.readLine();

    while (line != null) {
      strBuiler.append(line).append("\n");
      line = br.readLine();
    }

    System.out.println(strBuiler.toString());
  }
}
Output
This is a sample test file for demo.
It is a small txt file.

Java Program to Read a Text File as String using Scanner class

The Scanner class operates by separating the input into tokens that are received sequentially from the input stream. The Scanner class contains two in-build methods: next() and hasNext (). Both of these built-in methods return String objects.

We will create an instance of Path class where custom local directory path is passed as arguments to of() method of Path class. Then this file path object is used to initialze an scanner object. We then use the scanner object to read text file one line at a time using next() and hasNext() method.

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class ReadFileUsingScanner {
  public static void main(String args[]) throws Exception {
    Path fileName
            = Paths.get("techcrashcourse.txt");
    // Creating an object of Scanner class
    Scanner sc = new Scanner(fileName);
    while (sc.hasNext()) {
      // Iterating line by line over content of text file
      System.out.println(sc.nextLine());
    }
  }
}
Output
This is a sample test file for demo.
It is a small txt file.