Java读取txt最后一行首ID自增报错,求代码修复方案
修复读取文件最后一行ID时的NumberFormatException问题
需求是在FileManager类的proxId方法中,读取pedidos.txt的最后一行有效文本,提取该行首个数字ID并加1后返回。
文件内容示例:
0,1,2,44.5,1 1,2,3,54.25,3
(注:文件末尾存在空行)
当前使用的代码:
public static int proxId() throws IOException{ int proxId = 0; BufferedReader bufferedReader = new BufferedReader(new FileReader("-filepath-pedidos.txt")); String linha = ""; while ((linha = bufferedReader.readLine()) != null){ var aaa = linha.split(","); proxId = Integer.parseInt(aaa[0])+1; } return proxId; }
运行时抛出错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:675) at java.base/java.lang.Integer.parseInt(Integer.java:781) at file_manager.FileManager.proxId(FileManager.java:41)
错误原因
文件末尾的空行被readLine()读取后得到空字符串,执行split(",")后数组的第一个元素是空字符串,调用Integer.parseInt("")直接触发NumberFormatException。
修复后的代码
public static int proxId() throws IOException{ int proxId = 0; // 使用try-with-resources自动关闭流,避免资源泄漏 try (BufferedReader bufferedReader = new BufferedReader(new FileReader("-filepath-pedidos.txt"))) { String linha; while ((linha = bufferedReader.readLine()) != null) { // 跳过空行或仅含空白字符的无效行 String trimmedLine = linha.trim(); if (trimmedLine.isEmpty()) { continue; } String[] parts = trimmedLine.split(","); // 校验行格式:确保分割后有有效元素,且第一个元素是数字 if (parts.length > 0 && parts[0].matches("\\d+")) { proxId = Integer.parseInt(parts[0]) + 1; } } } return proxId; }
关键改动说明
- 过滤无效行:通过
trim()和空值判断,跳过文件末尾的空行或仅含空白字符的行,避免处理无效内容。 - 增强格式校验:用正则
\\d+判断第一个元素是否为纯数字,同时校验分割后的数组长度,避免因行格式错误触发异常。 - 优化资源管理:使用
try-with-resources语法,自动关闭BufferedReader,符合Java资源管理的最佳实践。
内容的提问来源于stack exchange,提问作者Eduardo Zaduski
相关产品推荐
相关产品推荐

