我想你可能有一个UTF-8 BOM(字节顺序标记)在你的文件的开始。
下面是重现该错误的类:
import java.io.*;
public class BomTest {
public static void main(String[] args) throws Exception {
File file = new File("example.txt");
// Write out UTF-8 BOM, followed by the number 22 and a newline.
byte[] bs = { (byte)0xef, (byte)0xbb, (byte)0xbf, (byte)'2', (byte)'2', 10 };
FileOutputStream fos = new FileOutputStream(file);
fos.write(bs);
fos.close();
BufferedReader r = new BufferedReader(new FileReader(file));
String s = r.readLine();
System.out.println(Integer.parseInt(s));
}
}
当我运行这个类,我得到下面的输出:
[email protected]:~$ java BomTest
Exception in thread "main" java.lang.NumberFormatException: For input string: "22"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at BomTest.main(BomTest.java:15)
是不是真的有一个简单的方法来处理UTF -8 Java中的BOM;最好不要生成它们。另请参阅this answer。
什么是例外,我们可以看到异常的堆栈跟踪多一点代码。 – blackpanther 2013-04-21 19:12:41