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.

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.

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 the 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.

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)

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 an 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 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.|


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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.