w3resource

Java: Read a file content line by line

Java Input-Output: Exercise-11 with Solution

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

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to read contents from a file into byte array.
Next: Write a Java program to read a plain text file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/io/java-io-exercise-11.php