w3resource

Java: Store text file content line by line into an array


14. Store File Lines in Array

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

Sample Solution:

Java 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 Exercise14 {
 
    public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
        List<String> list = new ArrayList<String>();
        try {
             BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
              while (strLine != null)
               {
                strLine = br.readLine();
                sb.append(strLine);
                sb.append(System.lineSeparator());
                strLine = br.readLine();
                if (strLine==null)
                   break;
                list.add(strLine);
            }
         System.out.println(Arrays.toString(list.toArray()));
             br.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
        }
     }
}

Sample Output:

[Append this text.Append this text.Append this text., Append this text., Append this text.]    

Flowchart:

Flowchart: Store text file content line by line into an array


For more Practice: Solve these Related Problems:

  • Write a Java program to read a file and store each line as an element in a String array.
  • Write a Java program to load file content into an array and then sort the lines alphabetically.
  • Write a Java program to read a text file into an array and print only the lines that contain a specified keyword.
  • Write a Java program to convert file lines into an array and then reverse the order of the lines.

Go to:


PREV : Store File Lines in Variable.
NEXT : Write and Read Text File.

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.