为什么Integer.parseInt在看似有效的输入上抛出NumberFormatException?

Ver*_*a D 3 java file-io encoding parsing inputstream

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

我在监视窗口中检查了parseInt函数的输入确实是一个看似有效整数的字符串(例如"35").但是,当我尝试str.charAtstr保持值为"35"的变量上使用该函数时,我得到了奇怪的结果:

str.charAt(0) == ""
str.charAt(1) == "3"
str.charAt(2) == ""
str.charAt(3) == "5"
Run Code Online (Sandbox Code Playgroud)

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

InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

(我在编辑器中使用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...

         }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

我的猜测是它实际上是:

str.charAt(0) == '\0'
str.charAt(1) == '3'
str.charAt(2) == '\0'
str.charAt(3) == '5'
Run Code Online (Sandbox Code Playgroud)

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

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