try {
bb = new BufferedReader(new InputStreamReader(
new FileInputStream(new File("F:\\测试2.txt"))));
String string = null;
while((string = bb.readLine()) != null) {
int ll = Integer.valueOf(string);
System.out.println(ll);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}finally {
try {
bb.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}文件第一行存了1,第二行存了3,为什么抛出java.lang.NumberFormatException,没有其他的字符啊

解决方案 »

  1.   

    仔细检查下"测试2.txt"文件中存放的数据有没有非数字的字符,如果有的话int ll = Integer.valueOf(string);这句会抛NumberFormatException异常的。这也是这段代码中唯一有肯能抛出此异常的地方。
    测试了一下这段代码如果文件存放的数据都是数字字符,是可以正常运行的。
    仅供参考package com.study.nio;import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;public class Answer50
    { public static void main(String[] args)
    {
    // TODO Auto-generated method stub
    BufferedReader bb = null;
    try
    {
    bb = new BufferedReader(new InputStreamReader(new FileInputStream(
    new File("F:\\测试2.txt"))));
    String string = null;
    while ((string = bb.readLine()) != null)
    {
    int ll = Integer.valueOf(string);
    System.out.println(ll);
    }
    }
    catch (FileNotFoundException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    finally
    {
    try
    {
    bb.close();
    }
    catch (IOException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } }}
      

  2.   


    while ((string = bb.readLine()) != null && string.trim().length()!=0)
                {
                    int ll = Integer.valueOf(string);
                    System.out.println(ll);
                }
      

  3.   

    那把读出来的strin检查一下是否是数字,再转换试下while ((string = bb.readLine()) != null
    && string.matches("\\d+"))
    {
    int ll = Integer.valueOf(string);
    System.out.println(ll); }