首页 > 解决方案 > 我错过了什么?NumberFormatException 错误

问题描述

我想从只包含数字的 txt 文件中读取。此类文件采用 UTF-8 格式,数字仅由换行符分隔(没有空格或任何其他内容)。每当我调用 Integer.valueOf(myString) 时,我都会遇到异常。

这个异常真的很奇怪,因为如果我创建一个预定义的字符串,例如“56\n”,并使用.trim(),它就可以完美地工作。但是在我的代码中,不仅不是这种情况,而且异常文本说它无法转换的是“54856”。我试图在那里引入一个新行,然后错误文本说它无法转换“54856”,这是不可能的,我错过了什么?

File ficheroEntrada = new File("C:\\in.txt");
FileReader entrada =new FileReader(ficheroEntrada);
BufferedReader input = new BufferedReader(entrada);

String s = input.readLine();
System.out.println(s);
Integer in;
in = Integer.valueOf(s.trim());
System.out.println(in);

异常文本如下:

Exception in thread "main" java.lang.NumberFormatException: For input string: "54856"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:658)
    at java.base/java.lang.Integer.valueOf(Integer.java:989)
    at Quicksort.main(Quicksort.java:170)

in.txt 文件包括:

54856
896
54
53
2
5634

标签: javastringfilecasting

解决方案


好吧,显然它与 Windows 和它使用的那些 \r 有关......我只是尝试在 Linux VM 上执行它并且它有效。感谢所有回答的人!!


推荐阅读