try {
            
            br = new BufferedReader(new FileReader(file));
            String a = br.readLine();
            System.out.println("The first line is:"  +a);
            int b = Integer.valueOf(a);//这里有问题。
输出如下,我是从一个txt文件里读东西。能把第一行的22读进来,但是将String的22转化为Integer的时候出了问题。
The first line is:22// 这里输出正确
java.lang.NumberFormatException: For input string: "22"求高人解答String IntegerString 转化Integer

解决方案 »

  1.   

    那你用int b = Integer.parseInt(a);试试呢,我没有用过valueOf,一直都是用parseInt的。
      

  2.   

    改成int b = Integer.parseInt(a.trim());试试看,也有可能是有空格之类的字符呢。
      

  3.   

    前后有空格。
    建议使用Integer.parseInt() 这个方法会自动去除空格,并且如果包括字符时也会自动去掉的 
      

  4.   

    public class StringTest {
    public static void main(String[] args) {
    File file = new File("D:/123.txt");
    int i = 0;
    BufferedReader br;
    String[] strArray = new String[1000];
    try {
    br = new BufferedReader(new FileReader(file)); while ((strArray[i++] = br.readLine()) != null) {
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    String a = null;
    for(i=0;i<strArray.length;i++){
    //doSomething
    if(strArray[0]!=null){
    a = strArray[0];
    }
    }
    System.out.println("The first line is:" + a);
    System.out.println("Length:" + a.length());//utf-8这里是2,utf-8 bom 这里是3
    int b = Integer.valueOf(a.trim());//
    System.err.println("b:" + b);
    }
    }
    刚刚运行了下你的代码,在我的机器上也出现了这样的问题。
    发现这是编码的问题。
    一般用记事本编辑过的UTF-8的文件头会加入BOM标识,该标识由3个char组成。
    利用EmEditor、Editplus等文本编辑器重新保存文件为不带BOM的UTF-8格式 问题就可以解决了。