w3resource

Java: Read a file line by line and store it into a variable


13. Store File Lines in Variable

Write a Java program to read a file line by line and store it in a variable.

Sample Solution:

Java Code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
 
public class exercise13 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        String str_data = "";
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
             while (strLine != null)
             {
                if (strLine == null)
                  break;
                str_data += strLine;
                strLine = br.readLine();
                
            }
              System.out.println(str_data);
             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 line by line and store it into a variable


For more Practice: Solve these Related Problems:

  • Write a Java program to read the entire content of a file into a single String variable.
  • Write a Java program to store file contents in a variable and then search for a specific substring within it.
  • Write a Java program to read a text file into a variable and count the number of occurrences of a given word.
  • Write a Java program to load a file's content into a variable and then split the text based on a delimiter.

Go to:


PREV : Read Plain Text File.
NEXT : Store File Lines in Array.

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.