java.lang.NumberFormatException:对于输入字符串:“ 22” [英] java.lang.NumberFormatException: For input string: "22"

查看:169
本文介绍了java.lang.NumberFormatException:对于输入字符串:“ 22”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void loadFromFile(String filename) {
    File file = new File(filename);
    BufferedReader br;

    try {
        br = new BufferedReader(new FileReader(file));
        numberOfAttributes = Integer.parseInt(br.readLine());
    } 
    ...
}

以上是我的程序:我正在尝试从txt文件读取,其中第一行是数字22,仅此而已。我不知道为什么程序会给我一个例外。

Above is my program: I am trying to read from a txt file where the first line is the number 22 and nothing more. I don't know why the program gives me an exception.

推荐答案

我认为您可能拥有UTF-8 BOM(字节序号)。

I think you might have a UTF-8 BOM (byte-order mark) at the start of your file.

以下是一个会重现错误的类:

Here's a class that reproduces the error:

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));
    }
}

运行此类时,得到以下输出:

When I run this class, I get the following output:

luke@computer:~$ 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)

用Java处理UTF-8 BOM并不是一种简单的方法。最好不要首先生成它们。另请参见此答案

There isn't really an easy way to deal with UTF-8 BOMs in Java; it's best not to generate them in the first place. See also this answer.

这篇关于java.lang.NumberFormatException:对于输入字符串:“ 22”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆