Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store text file content line by line into array

Tags:

java

arrays

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();
            }
        }
like image 840
salemkhoo Avatar asked Apr 19 '13 08:04

salemkhoo


People also ask

How do you store the contents of a file in an array?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

Can an array store text?

You can store multiple pieces of text in a string array. Each element of the array can contain a string having a different number of characters, without padding.

How do you read a text file and store it to an array in Java?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.


1 Answers

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

like image 58
Evgeniy Dorofeev Avatar answered Sep 28 '22 12:09

Evgeniy Dorofeev