Write a Java program to store text file content line by line into an array


This Java code reads the contents of a text file named "file.txt", stores them in a StringBuilder and an ArrayList, and prints the contents of the ArrayList to the console. Here's a step-by-step explanation of the code:

  • The StoreText class is defined.
  • In the main method, a StringBuilder object named strBuil is initialized to store the contents of the text file.
  • A String variable named str is also initialized to store each line of the text file.
  • A List<String> object named list is initialized to store each line of the text file.
  • A try-catch block is used to handle any exceptions that may occur while reading the text file.
  • A BufferedReader object named bufRead is initialized to read the contents of the text file.
  • A while loop is used to read each line of the text file using the readLine method of the bufRead object.
  • Inside the loop, each line of the text file is appended to the strBuil object using the append method and the system's line separator is also appended to ensure that each line is printed on a new line.
  • The same line is also added to the list object using the add method.
  • If the current line is null, the loop is broken using the break statement.
  • After the loop has completed, the contents of the list object are printed to the console using the toString method and the toArray method of the List object.
  • The bufRead object is closed using the close method.
  • FileNotFoundException and IOException are caught in separate catch blocks, and an error message is printed to the console in case an exception occurs.

Source Code

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
 
public class StoreText
{ 
    public static void main(String a[])
	{
        StringBuilder strBuil = new StringBuilder();
        String str = "";
        List<String> list = new ArrayList<String>();
        try
		{
			BufferedReader bufRead = new BufferedReader(new FileReader("file.txt"));
			while(str != null)
			{
				str = bufRead.readLine();
				strBuil.append(str);
				strBuil.append(System.lineSeparator());
				str = bufRead.readLine();
				if (str==null)
				{
					break;
				}
				list.add(str);
			}
			System.out.println(Arrays.toString(list.toArray()));
			bufRead.close();
        }
		catch(FileNotFoundException e)
		{
            System.err.println("File Not found");
        }
		catch(IOException e)
		{
            System.err.println("Unable to Read the File.");
        }
     }
}
 

Output

[]