Java读取文本文件触发NumberFormatException异常的问题求助
解决Java读取文本中多个整数时的NumberFormatException问题
你遇到的这个异常原因很明确:你的代码用nextLine()读取了整一行内容,然后试图把整串包含多个空格分隔数字的字符串转成单个整数——比如第二行的"650 64 1"显然不是一个合法的整数格式,所以直接触发了NumberFormatException。
这里给你两种实用的解决方案,根据你的需求选择即可:
方案1:用Scanner原生方法逐个读取整数(推荐)
Scanner本身就支持跳过空格、换行等空白字符,直接读取单个整数,不需要手动处理行内容。修改后的代码如下:
import java.util.Scanner; import java.io.*; class Test{ public static void main(String[] args){ String filnavn = "regneklynge.txt"; Scanner innFil = null; try { File fil = new File(filnavn); innFil = new Scanner(fil); // 检查是否还有下一个整数可读 while (innFil.hasNextInt()) { int tall = innFil.nextInt(); System.out.println(tall); } } catch(FileNotFoundException e) { System.out.println("Filen kunne ikke finnes"); } finally { // 关闭Scanner,避免资源泄漏 if (innFil != null) { innFil.close(); } } } }
说明:
hasNextInt()会自动扫描输入流,判断是否存在下一个合法整数;nextInt()会跳过所有空白字符(空格、换行、制表符等),直接返回下一个整数,完美适配你的文本格式;- 新增的
finally块用于关闭Scanner,这是Java资源管理的良好习惯,避免不必要的资源占用。
方案2:先读取整行,再拆分转换(适合需要处理整行逻辑的场景)
如果你确实需要先获取整行内容再处理,可以用split()方法把行字符串按空格拆分,再逐个转换为整数:
import java.util.Scanner; import java.io.*; class Test{ public static void main(String[] args){ String filnavn = "regneklynge.txt"; Scanner innFil = null; try { File fil = new File(filnavn); innFil = new Scanner(fil); while (innFil.hasNextLine()) { String linje = innFil.nextLine(); // 用正则表达式\\s+匹配任意数量的空白字符,拆分整行 String[] tallStrenger = linje.split("\\s+"); for (String tallStr : tallStrenger) { // 跳过可能的空字符串(比如行首/行尾的空格) if (!tallStr.isEmpty()) { int tall = Integer.parseInt(tallStr); System.out.println(tall); } } } } catch(FileNotFoundException e) { System.out.println("Filen kunne ikke finnes"); } catch(NumberFormatException e) { // 额外捕获单个数字转换失败的情况,让程序更健壮 System.out.println("Kunne ikke konvertere til tall: " + e.getMessage()); } finally { if (innFil != null) { innFil.close(); } } } }
说明:
split("\\s+")可以处理多个连续空格的情况,避免拆分出空字符串;- 新增的
NumberFormatException捕获逻辑,可以在某个数字格式不合法时给出提示,而不是直接终止程序; - 适合需要对整行内容做额外处理(比如统计每行数字数量)的场景。
内容的提问来源于stack exchange,提问作者pkrist
相关产品推荐
相关产品推荐

