w3resource

Java: Read a plain text file


12. Read Plain Text File

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.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
 
public class Exercise12 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
             while (strLine != null)
             {
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                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.                                                                                             
null 

Flowchart:

Flowchart: Read a plain text file


For more Practice: Solve these Related Problems:

  • Write a Java program to read a plain text file and display its contents to the console.
  • Write a Java program to read a text file into a String and print the length of the resulting text.
  • Write a Java program to read a plain text file and count the frequency of each word present.
  • Write a Java program to read a text file and output the content in reverse order.

Go to:


PREV : Read File Line by Line.
NEXT : Store File Lines in Variable.

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.