我有这种方法只读取文件中的数字并将其存储到两个不同的arraylists中,每行一个。它将该行存储为字符串,因此它只有一个索引。
如何从文件中读取并分离所有数字,以便获得索引0-14,因为我需要它们以便稍后进行计算?
该文件包含:
vot1:8,8,9,1,7,6,8,8,9,5,6,8,7,9,8
vot2:7,8,8,8,9,4,7,8,10,7,8,9,8,8,9
我的代码是:
public void readFileTest(String path) throws FileNotFoundException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
String line = null;
int x=0;
while ((line = br.readLine()) != null) {
x++;
if (x<2){
line = line.substring(line.indexOf(":") + 1);
numbers.addAll(Arrays.asList(line.split(",")));
}else{
line = line.substring(line.indexOf(":") + 1);
numbers1.addAll(Arrays.asList(line.split(",")));
}
}
} catch (FileNotFoundException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
for (Object c : numbers) {
System.out.print(c);
}
System.out.println();
for (Object c : numbers1) {
System.out.print(c);
}
}
答案 0 :(得分:2)
使用numbers.addAll(Arrays.asList(line.split(",")))
。