salemkhoo salemkhoo - 28 days ago 19
Java Question

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();
}
}

Answer

I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.

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

List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

String[] stringArr = list.toArray(new String[0]);