将文本文件内容逐行存储到数组中 [英] Store text file content line by line into array
问题描述
all,我现在面临着不知道将文本文件中的内容存储到数组中的问题.情况是这样的,文本文件内容:
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.
代码是:
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();
}
}
推荐答案
我建议使用 ArrayList
,它处理动态大小调整,而数组需要预先定义大小,您可以不知道.您始终可以将列表重新转换为数组.
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]);
这篇关于将文本文件内容逐行存储到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!