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)
public class ReadFile
public static void main(String arfs)
try(BufferedReader br=new BufferedReader(new FileReader("C:/Desktop/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,