我想从只包含数字的txt文件中读取。这样的文件是 UTF-8 格式,数字仅由新行(没有空格或任何其他内容(分隔。每当我调用 Integer.valueOf(myString( 时,我都会得到异常。
这个异常真的很奇怪,因为如果我创建一个预定义的字符串,例如"56",并使用 .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)
.txt 中的文件包括:
54856
896
54
53
2
5634
,它与Windows和它使用的那些\r有关......我只是尝试在 Linux VM 上执行它,它起作用了。感谢所有回答的人!!
尝试用类Scanner
读取文件,使用它hasNextInt()
方法来识别您正在读取的内容是否Integer
。这将帮助您找出导致问题的字符串/字符
public static void main(String[] args) throws Exception {
File ficheroEntrada = new File(
"C:\in.txt");
Scanner scan = new Scanner(ficheroEntrada);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("found integer" + scan.nextInt());
} else {
System.out.println("not integer" + scan.next());
}
}
}
<</div>
div class="one_answers"> 如果你想确保字符串的可解析性,你可以使用一个模式和正则表达式。
Pattern intPattern = Pattern.compile("\-?\d+");
Matcher matcher = intPattern.matcher(input);
if (matcher.find()) {
int value = Integer.parseInt(matcher.group(0));
// ... do something with the result.
} else {
// ... handle unparsable line.
}
此模式允许任何数字和可选的减号(不带空格(。它应该肯定解析,除非它太长。我不知道它如何处理这个问题,但您的示例似乎主要包含短整数,所以这无关紧要。
很可能你的输入中有一个leading/trailing whitespaces
,如下所示:
String s = " 5436";
System.out.println(s);
Integer in;
in = Integer.valueOf(s.trim());
System.out.println(in);
在字符串上使用trim()
来摆脱它。
UPDATE 2:
如果您的文件包含以下内容:
54856n
896
54n
53
2n
5634
然后使用以下代码:
....your code
FileReader enter = new FileReader(file);
BufferedReader input = new BufferedReader(enter);
String currentLine;
while ((currentLine = input.readLine()) != null) {
Integer in;
//get rid of non-numbers
in = Integer.valueOf(currentLine.replaceAll("\D+",""));
System.out.println(in);
...your code