You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取TXT文件时抛出NumberFormatException异常求助

解决Java读取文本文件时的NumberFormatException异常

嘿,我来帮你搞定这个问题!你遇到的NumberFormatException其实很常见——就是代码里尝试把**空字符串("")**转换成Integer类型的时候翻车了,Integer.parseInt()方法根本没法处理空内容,直接就抛出异常终止程序了。

问题定位

先去你代码里找调用Integer.parseInt()的地方,大概率是这几种情况:

  • 读取文件时拿到了空白行,直接拿去转整数
  • 按分隔符拆分文件内容时,得到了空的字段(比如一行里有多个连续分隔符)
  • 文件里的内容本身就包含全空白的字符串(比如只有空格、制表符)

解决方案

这里给你几个实用的处理方式,按需选择:

1. 提前校验,过滤无效内容

在转换之前先判断字符串是否有效,避免触发异常:

String inputStr = "从文件读取的内容";
// 先去掉前后空白,再判断是否为空
String trimmedStr = inputStr.trim();
if (!trimmedStr.isEmpty()) {
    int num = Integer.parseInt(trimmedStr);
    // 正常处理数字逻辑
} else {
    // 遇到空内容时的处理:跳过、打印提示都行
    System.out.println("跳过无效的空数据");
}

2. 捕获异常,避免程序崩溃

如果没法提前预判所有无效情况,就用try-catch把转换代码包裹起来,优雅处理错误:

String inputStr = "从文件读取的内容";
try {
    int num = Integer.parseInt(inputStr.trim());
    // 正常处理数字
} catch (NumberFormatException e) {
    // 打印错误信息或者做其他处理,程序不会直接崩溃
    System.out.println("无法将内容'" + inputStr + "'转为整数:" + e.getMessage());
}

3. 检查并清理源文件

如果是文件本身有问题(比如大量空白行、无效字符),可以先手动清理文件,或者在读取时直接过滤掉无效行:

// 读取文件时跳过空白行
String line = br.readLine();
if (line == null || line.trim().isEmpty()) {
    continue; // 跳过当前行,继续读下一行
}

完整示例代码

给你一个改进后的读取文件类,整合了上面的处理逻辑:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class LerArquivo {
    public static void main(String[] args) {
        // 替换成你的文件路径
        String filePath = "test.txt";
        
        // 使用try-with-resources自动关闭流
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String trimmedLine = line.trim();
                // 跳过空白行
                if (trimmedLine.isEmpty()) {
                    System.out.println("跳过空白行");
                    continue;
                }
                // 尝试转换为整数并处理异常
                try {
                    int number = Integer.parseInt(trimmedLine);
                    System.out.println("读取到有效数字:" + number);
                } catch (NumberFormatException e) {
                    System.out.println("行内容[" + line + "]不是有效整数,跳过:" + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误:" + e.getMessage());
        }
    }
}

内容的提问来源于stack exchange,提问作者Kakashi - Sensei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:06:55