请教一个问题: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]中
------解决方案--------------------
仅供参考:
- Java code
public static void main(String[] arg) throws Exception{ 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; } }
------解决方案--------------------
- Java code
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)); }