w3resource

Java: Read a file content line by line


11. Read File Line by Line

Write a Java program to read file content line by line.

Sample Solution:

Java Code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
public class Exercise11 {
 
    public static void main(String a[]){
        BufferedReader br = null;
        String strLine = "";
        try {
            br = new BufferedReader( new FileReader("/home/students/test.txt"));
            while( (strLine = br.readLine()) != null){
                System.out.println(strLine);
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

Sample Output:

Welcome to w3resource.com.                                                                                    
Append this text.Append this text.Append this text.                                                           
Append this text.                                                                                             
Append this text.                                                                                             
Append this text.                                                                                             
Append this text.

Flowchart:

Flowchart: Read a file content line by line


For more Practice: Solve these Related Problems:

  • Write a Java program to read a text file line by line and display each line along with its line number.
  • Write a Java program to read a file line by line and count the total number of lines.
  • Write a Java program to read a file line by line using BufferedReader and store the lines in a List.
  • Write a Java program to read a file line by line and filter out lines that do not contain a specified keyword.

Go to:


PREV : Read File into Byte Array.
NEXT : Read Plain Text File.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.