如何将文本文件内容保存到不同的数组?
我的文本文件内容是这样的;
12 14 16 18 13 17 14 18 10 23
pic1 pic2 pic3 pic4 pic5 pic6 pic7 pic8 pic9 pic10
left right top left right right top top left right
100 200 300 400 500 600 700 800 900 1000
如何将每一行保存到不同的数组中? e.g。
line 1 will be saved in an array1
line 2 will be saved in an array2
line 3 will be saved in an array3
line 4 will be saved in an array4
答案 0 :(得分:3)
解决方案1
List<String[]> arrays = new ArrayList<String[]>(); //You need an array list of arrays since you dont know how many lines does the text file has
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
String arr[] = str.split(" ");
if(arr.length>0) arrays.add(arr);
}
in.close();
} catch (IOException e) {
}
最后,数组将包含每个数组。在您的示例arrays.length()==4
迭代数组:
for( String[] myarr : arrays){
//Do something with myarr
}
解决方案2:我认为这不是一个好主意,但如果您确定文件总是包含4行,则可以执行此操作
String arr1[];
String arr2[];
String arr3[];
String arr4[];
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
str = in.readLine();
arr1[] = str.split(" ");
str = in.readLine();
arr2[] = str.split(" ");
str = in.readLine();
arr3[] = str.split(" ");
str = in.readLine();
arr4[] = str.split(" ");
in.close();
} catch (IOException e) {
}
答案 1 :(得分:1)
查看String [] split