【问题标题】:Why does the Integer.parseInt throw NumberFormatException on input that seems valid?为什么 Integer.parseInt 在看起来有效的输入上抛出 NumberFormatException?
【发布时间】:2011-01-16 07:58:09
【问题描述】:

我正在从书中做一个简单的练习,我对 java 函数 parseInt 的工作原理有点困惑。我从输入文件中读取了一行,使用 StringTokenizer 对其进行拆分,现在我想将每个部分解析为整数。

我在监视窗口中检查了 parseInt 函数的输入确实是一个看起来是有效整数的字符串(例如“35”)。但是,当我尝试对持有值“35”的变量 str 使用 str.charAt 函数时,我得到了奇怪的结果:

str.charAt(0) == ""
str.charAt(1) == "3"
str.charAt(2) == ""
str.charAt(3) == "5"

这似乎是一个可能与编码有关的问题,所以我尝试使用这种读取文件的方式来修复它:

InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");

(我已在我的编辑器中使用 UTF-8 编码明确保存了文件),但这并没有帮助。任何想法可能是什么问题以及如何解决它?

编辑:我的示例

        InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");
        BufferedReader bfreader = new BufferedReader(reader);

        line = bfreader.readLine();
        while (line !=null)
        {
                String[] valueStrings = line.split(" ");
                String hole = valueStrings[0]; 

                int[] values = new int[4];
                for (int i = 0; i <values.length; i++){

                    String nr = valueStrings[i+1].trim(); 
                    values [i] = Integer.parseInt(nr);
                }

                // it breaks at the parseInt here, the rest is not even executed...

         }

【问题讨论】:

    标签: java encoding file-io parsing inputstream


    【解决方案1】:

    我的猜测是实际上

    str.charAt(0) == '\0'
    str.charAt(1) == '3'
    str.charAt(2) == '\0'
    str.charAt(3) == '5'
    

    听起来它实际上可能以 UTF-16 而不是 UTF-8 保存 - 但如果您的文本编辑器认为 意味着 保存“空”字符,那将是有道理的。尝试在二进制十六进制编辑器中查看文本文件 - 我怀疑你会发现每隔一个字节都是 0。

    如果这没有帮助,请发布一个简短但完整的程序来演示该问题 - 到目前为止,我们只看到了您的一行代码。

    【讨论】:

    • 其实你是对的,我已经在十六进制编辑器中检查过了,每个第二个字符都是零。无论如何,我怎样才能从这样的文件中读取?
    • 将字符集设置为 UTF-16 应将其读入,或者将文件保存为 UTF-8 或系统默认值。
    • 文件读入很好,问题是parseInt在尝试解析字符串时失败。有什么办法可以解决吗?
    • @KateM:不,如果您的字符串中所有其他字符都作为 Unicode 字符“\0”,那么它不是可以正常读取。
    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 2021-04-09
    • 2015-07-16
    • 1970-01-01
    • 2022-07-26
    • 2012-01-29
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多