请教一个问题:java 怎么读文件中的一行数据 存到数组中要读的是txt文件
我截了一行 格式如下1545 2034 2578 1582 1495 454 2142 825 842 2405 3098 2872 3093 631 3225 1393 3378 715 2972 513每行20个数字,中间用空格隔开的,想要读取出来,把这20个数存到int类型的数组list[20]中
我截了一行 格式如下1545 2034 2578 1582 1495 454 2142 825 842 2405 3098 2872 3093 631 3225 1393 3378 715 2972 513每行20个数字,中间用空格隔开的,想要读取出来,把这20个数存到int类型的数组list[20]中
BufferedReader reader = new BufferedReader(new FileReader(""));
List<Integer> values = new ArrayList<Integer>();
while(true){
String line = reader.readLine();
if(line == null){
break;
}
String[] vStrs = line.split("\\s+");
for(String str : vStrs){
values.add(Integer.valueOf(str));
}
}
int[] array = new int[values.size()];
int i = 0;
for(Integer v : values){
array[i++] = v;
}
}
public static void main(String[] arg) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("E:/test.txt"));
int[] list = new int[20];
int i = 0;
String line = null;
while ((line = reader.readLine()) != null) {
String[] vStrs = line.split(" ");
for (String str : vStrs) {
list[i++] = Integer.parseInt(str);
}
}
System.out.println(Arrays.toString(list));
}
java.lang.ArrayIndexOutOfBoundsException
String[] vStrs = line.split(" ");System.out.println("-------打印出来,看拆分了几段----:" + vStrs.length) ;
//应该大于 20 了
for (String str : vStrs) {
list[i++] = Integer.parseInt(str);
}
}