ToB*_*eek 2 java exception number-formatting
public void loadFromFile(String filename) {
File file = new File(filename);
BufferedReader br;
try {
br = new BufferedReader(new FileReader(file));
numberOfAttributes = Integer.parseInt(br.readLine());
}
...
}
Run Code Online (Sandbox Code Playgroud)
以上是我的程序:我试图从一个txt文件中读取第一行是数字22,仅此而已.我不知道为什么程序会给我一个例外.
尝试从字符串中删除任何空格:
numberOfAttributes = Integer.parseInt(br.readLine().trim());
Run Code Online (Sandbox Code Playgroud)
我认为您可能在文件的开头有一个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));
}
}
Run Code Online (Sandbox Code Playgroud)
运行此类时,将得到以下输出:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
在Java中,实际上没有一种简单的方法可以处理UTF-8 BOM。最好不要首先生成它们。另请参阅此答案。
| 归档时间: |
|
| 查看次数: |
27644 次 |
| 最近记录: |