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

Java Input-Output: Exercise-13 with Solution

Write a java program to read a file line by line and store it into 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)
                str_data += strLine;
                strLine = br.readLine();
        } 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: Read a file line by line and store it into a variable

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to read a plain text file.
Next: Write a Java program to store text file content line by line into an array.

What is the difficulty level of this exercise?

Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH