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)

import java.io.BufferedReader;
import java.io.FileReader;


public class ReadFile 
{
    public static void main(String arfs[])
    {
    
    try(BufferedReader br=new BufferedReader(new FileReader("C:/Desktop/Sample.txt")))
    {
        String lineReader=null;
        
        while((lineReader=br.readLine())!=null)
        {
            System.out.println(lineReader);
        }
    }
    catch(Exception e)
    {
        
    }
    }
}

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,

Output:
op1

By Sri

Leave a Reply

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