[java] Store text file content line by line into array

all,I'm now facing the problem of no idea on storing the content in text file into the array. The situation is like, text file content:

abc1
xyz2
rxy3

I wish to store them into array line by line, is that possible? What I expect is like this:

arr[0] = abc1
arr[1] = xyz2
arr[2] = rxy3

I've try something like this, but seem like not work for me. If anyone can help me, really thanks a lot.

The code is:

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
        String str;

        while((str = in.readLine()) != null){
            String[] arr = str.split(" ");
            for(int i=0 ; i<str.length() ; i++){
                arr[i] = in.readLine();
            }
        }

This question is related to java arrays

The answer is


You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7


This should work because it uses List as you don't know how many lines will be there in the file and also they may change later.

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
    lines.add(str);
}
String[] linesArray = lines.toArray(new String[lines.size()]);

Suggest use Apache IOUtils.readLines for this. See link below.

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html


Just use Apache Commons IO

List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));

You need to do something like this for your case:-

int i = 0;
while((str = in.readLine()) != null){
    arr[i] = str;
    i++;
}

But note that the arr should be declared properly, according to the number of entries in your file.

Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)


When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> output = new LinkedList<String>();

while((str = in.readLine()) != null){
    output.add(str);
}

String[] arr = output.toArray(new String[output.size()]);

Try this:

String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)          
    arr[i++] = str;

System.out.println(Arrays.toString(arr));

JAVA 8 :

Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());

You can use this full code for your problem. For more details you can check it on appucoder.com

class FileDemoTwo{
    public static void main(String args[])throws Exception{
        FileDemoTwo ob = new FileDemoTwo();
        BufferedReader in = new BufferedReader(new FileReader("read.txt"));
        String str;
        List<String> list = new ArrayList<String>();
        while((str =in.readLine()) != null ){
            list.add(str);
        }
        String[] stringArr = list.toArray(new String[0]);
        System.out.println(" "+Arrays.toString(stringArr)); 
    }

}