Read a file in java

Posted on Updated on

Java IO package contains classes which programmers are used to read content of a file . However, there are different ways to read content of a file and thus create dilemma to select one method over other. To select a efficient way, one should first consider nature of input file, content whether small or large and so on. In this blog, we have come up with different ways to read a file in Java with example.

  1. Read a file using FileReader
  2. Read a file using BufferedReader
  3. Read a file using Scanner class

 1) Read a file using FileReader

FileReader is meant for reading streams of characters. It is most efficient way to read a file, you can use FileReader if size of the file is small. Below examples demonstrate how to read a file using FileReader.

Output

2) Read a file using BufferedReader

BufferedReader is simplest and most commonly used class to read content of a file line by line. However, it is not most effective ways but due to simplicity, programmers love to use this class. Below example demonstrate how to read a file using BufferedReader.

Output

3) Read a file using Scanner class

We can use Scanner class to read the content of a file in java. It is not the efficient way. Scanner class contains several useful methods which return different tokens. So, it is useful if you want to parse content of the file while reading. Below example demonstrate how to read a file line by line using Scanner class.

Output

Conclusion : To read a small file, it is good to use FileReader which is efficient as compare to other methos. BufferedReader is good to read file line by line however if you want to parse content of a file while reading the content Scanner class is a good choice. There are some differences between BufferedReader and Scanner class which you can find in BufferedReader vs Scanner.

 

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.