Java:从一个文件读取整数到一个数组

File fil = new File("Tall.txt"); FileReader inputFil = new FileReader(fil); BufferedReader in = new BufferedReader(inputFil); int [] tall = new int [100]; String s =in.readLine(); while(s!=null) { int i = 0; tall[i] = Integer.parseInt(s); //this is line 19 System.out.println(tall[i]); s = in.readLine(); } in.close(); 

我正在尝试使用“Tall.txt”文件将其中包含的整数写入名为“tall”的数组中。 它在一定程度上做到了这一点,但是当我运行它时,会抛出以下exception(:

 Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at BinarySok.main(BinarySok.java:19) 

为什么它做到这一点,我该如何删除它? 就像我看到的那样,我把这个文件看作string,然后把它转换成整数,这不是非法的。

你可能想要做这样的事情(如果你在java 5以上)

 Scanner scanner = new Scanner(new File("tall.txt")); int [] tall = new int [100]; int i = 0; while(scanner.hasNextInt()){ tall[i++] = scanner.nextInt(); } 

您的文件中必须有一个空行。

您可能想要将您的parseInt调用包装在“try”块中:

 try { tall[i++] = Integer.parseInt(s); } catch (NumberFormatException ex) { continue; } 

或者只是在parsing之前检查空string:

 if (s.length() == 0) continue; 

请注意,通过在循环内初始化索引variablesi ,它始终为0.您应该在while循环之前移动声明。 (或使其成为for循环的一部分。)

为了比较,这里是读取文件的另一种方式。 它有一个好处,你不需要知道文件中有多less个整数。

 File file = new File("Tall.txt"); byte[] bytes = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytes); fis.close(); String[] valueStr = new String(bytes).trim().split("\\s+"); int[] tall = new int[valueStr.length]; for (int i = 0; i < valueStr.length; i++) tall[i] = Integer.parseInt(valueStr[i]); System.out.println(Arrays.asList(tall)); 

它看起来像Java试图将空string转换为数字。 在这个数字序列的最后是否有空行?

你可以像这样修复代码

 String s = in.readLine(); int i = 0; while (s != null) { // Skip empty lines. s = s.trim(); if (s.length() == 0) { continue; } tall[i] = Integer.parseInt(s); // This is line 19. System.out.println(tall[i]); s = in.readLine(); i++; } in.close(); 

您可能会在不同的行结尾之间混淆。 一个Windows文件将结束每一行回车和换行符。 Unix上的某些程序会读取该文件,就好像每行之间有一个额外的空行一样,因为它会将回车视为行结束,然后将行换行看作行的另一端。

 File file = new File("E:/Responsibility.txt"); Scanner scanner = new Scanner(file); List<Integer> integers = new ArrayList<>(); while (scanner.hasNext()) { if (scanner.hasNextInt()) { integers.add(scanner.nextInt()); } else { scanner.next(); } } System.out.println(integers);