Skip to content

Java Read File Text | Into String | Scanner | Read file line by line example


Reading text from a file or Read File is very important for any programming language. In this tutorial, you will learn How to “Java read file text” with an example. There are multiple ways to read a text file in a Java programming language.

Java Read File Text Into String Scanner Read file line by line example

Reading a text file in Java

Here are some different ways to read a file in java.

  • FileReader class
  • BufferedReader
  • Scanner class
  • Read text file using Files class

Java 8 is introduce java.util.stream.Stream which is a more efficient way to read a file in Java.

Let’s start Java read file text example with different ways 

We are covering some ways with an only text file, attaching screen how we arranged our project.

Classic BufferedReader

For this way, you need to import a java io (input/output/) package and BufferedReader file. Before that, you also need a File class to get the file. So FileReader and File both classes needed to import.

See the below example. For that assuming a file name is “filename.txt”. Below is a screenshot of the project for better understanding.

Java read file example with different way Classic BufferedReader

Here is a complete code.

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

public class FileReading {

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

        File file = new File("filename.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));

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

Output: Hello Buffer read the file

FileReader class

A FileReader class inherits from the InputStreamReader class and it’s used for reading streams of characters.

import java.io.FileReader;

public class FileReading {

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

        // pass the path of file
        FileReader fr = new FileReader("filename.txt");

        int i;
        while ((i = fr.read()) != -1)
            System.out.print((char) i);
    }
}

Output: FileReader read the file

Using Scanner class

For that, you need an import io package file class and util package scanner, class.

The Java Scanner class comes under java.util package. The Java Scanner class breaks the input into tokens using a delimiter. Where that is whitespace by default. This provides us with many methods to read and parse various primitive values.

import java.io.File;
import java.util.Scanner;

public class FileReading {

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

        // pass the path of file
        File file =
                new File("filename.txt");
        Scanner sc = new Scanner(file);

        while (sc.hasNextLine())
            System.out.println(sc.nextLine());
    }
}

Output: Scanner read the file

Read a File into a String

Let’s see the example of how java read file to string. (Read File to String in Java 8)

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FileReading {

    public static void main(String[] args) {
        String filePath = "filename.txt";

        System.out.println(readLineByLineJava(filePath));
    }


    private static String readLineByLineJava(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();

        try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
            stream.forEach(s -> contentBuilder.append(s).append("\n"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return contentBuilder.toString();
    }
}

Output: java read file line by line

Question: How to read data from a file in Java?

Answer: As above we How to read a file in Java, can do with other files like word, excel etc.

Maybe there is more way to do it example also if you think any other much better way should be in this tutorial, then please do comment. We will add this to others. And if you have any doubt and suggestion, then also do comment in the below section.

To read text from console follow this tutorial – Text from the console

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All How to read a file in Java are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|

1 thought on “Java Read File Text | Into String | Scanner | Read file line by line example”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading