输入字符串 "1"的 java.lang.NumberFormatException

标签 java parsing encoding

所以,我有一个真正困扰我的问题。我有一个用 java 制作的简单解析器。这是一段相关代码:

while( (line = br.readLine())!=null)
{
    String splitted[] = line.split(SPLITTER);
    int docNum = Integer.parseInt(splitted[0].trim());
    //do something
}

输入文件是 CSV 文件,文件的第一个条目是整数。当我开始解析时,我立即得到这个异常:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at dipl.parser.TableParser.parse(TableParser.java:50)
at dipl.parser.DocumentParser.main(DocumentParser.java:87)

我检查了文件,它的第一个值确实是 1(该字段中没有其他字符),但我仍然收到消息。我认为这可能是因为文件编码:它是 UTF-8,带有 Unix endlines。该程序在 Ubuntu 14.04 上运行。欢迎提出在哪里寻找问题的任何建议。

最佳答案

您有一个 BOM在那个号码前面;如果我在您的问题中复制类似于 "1" 的内容并将其粘贴到 vim 中,我看到您前面有一个 FE FF(例如 BOM )其中。从那个链接:

The exact bytes comprising the BOM will be whatever the Unicode character U+FEFF is converted into by that transformation format.

这就是问题所在,使用适当的阅读器来使用文件以进行文件编码的转换(UTF-8、UTF-16 big-endian、UTF-16 little-endian 等)。另见 this question and its answers有关在 Java 中读取 Unicode 文件的更多信息。

关于输入字符串 "1"的 java.lang.NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701215/

相关文章:

java - Spring 安全: remember-me cookie is created in the browser but password is not saving

java - 从列表中获取 Activity 对象

string - 使用 .NET 3.5 查找字符串中的第一个数字

ruby - 如何从 Unix 将 DOS 行结尾写入文件

java - Spring Autowired 组件在 bean 方法中为 null

java - 使用 root Android 应用程序运行二进制文件

ios - NSError 是否可以在 TBXML 中重用?

parsing - 解析器组合器 : how to terminate repetition on keyword

php - 阿拉伯字符插入 php mysql XML 解析错误 : not well-formed

java - 如何在 Android 9 上保持 UTF-8 的向后兼容性?