Reading from a Text File using Java

Reading from a Text File using Java
In this article, let us see how to read the data from text file using Java.

In Java, we can read the data using Reader and Streams.
Reader –  Reads or Writes one character at time
Streams – Reads or Writes byte by byte

Now let us see an example code for reading from a text file. For this example, I have created a text file with the data “Sample text file for Java purpose” and saved it with the name Sample (Sample.txt)

In the above code we have used Reader, BufferedReader and FileReader for reading the data from Sample.txt file.
In the code you can see that we have opened and read the file along with try() – This is known as Try with Resources. The advantage of using try with resources is, The resources get opened and automatically gets closed by itself.

When we run this code,


Leave a Reply

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