Java read text file With Examples

There are many ways to read a text file in java. Let’s look at java read text file different methods one by one.

Java read text file

java-read-text-file

There are many ways to read a text file in java. A text file is made of characters, so we can use Reader classes. There are some utility classes too to read a text file in java.

  1. Java read text file using Files class
  2. Read text file in java using FileReader
  3. Java read text file using BufferedReader
  4. Using Scanner class to read text file in java

Now let’s look at examples showing how to read a text file in java using these classes.

Java read text file using java.nio.file.Files

We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a list of string. Files class is introduced in Java 7 and it’s good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.

Read text file in java using java.io.FileReader

You can use FileReader to get the BufferedReader and then read files line by line. FileReader doesn’t support encoding and works with the system default encoding, so it’s not a very efficient way of reading a text file in java.

Java read text file using java.io.BufferedReader

BufferedReader is good if you want to read file line by line and process on them. It’s good for processing the large file and it supports encoding also.

BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.

Using scanner to read text file in java

If you want to read file line by line or based on some java regular expression, Scanner is the class to use.

Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner class is not synchronized and hence not thread safe.

Java Read File Example

Here is the example class showing how to read a text file in java. The example methods are using Scanner, Files, BufferedReader with Encoding support and FileReader.

The choice of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For example, if you are just logging the file, you can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, you should use Scanner class.

Before I end this tutorial, I want to mention about RandomAccessFile. We can use this to read text file in java.

That’s all for java read text file example programs.

By admin

Leave a Reply