0

从文件读取数据时出现空指针异常。如果它返回垃圾值如何处理。如果我不给修剪提供一些垃圾价值。我的代码是:

BufferedReader br = null;
try {           
    String sCurrentval = "";
    br = new BufferedReader(new FileReader("filepath"));
    while ((sCurrentval = br.readLine()) != null) {
        System.out.println("Reading from File "+sCurrentval);
    }
    if(sCurrentval != null){
        sCurrentval = sCurrentval.trim();
    }
    System.out.println("outside :  Reading from File "+sCurrentval);
    if(sCurrentval != null && !sCurrentval.equalsIgnorecase("")){
        try{
            val = Integer.parseInt(sCurrentval.trim());
        }catch(Exception e){
            e.printStackTrace();
        }
    }else{
        System.out.println("Reading Value  null ");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (br != null)br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
4

1 回答 1

1

BufferedReader br = null;try. 但是您finally也使用相同的变量br

 try
    {
    //
    BufferedReader br = null; // declared with in try
    //
    }
    finally {
    try {
    if (br != null) // In this line the br is not identified 
     br.close();
    } catch (IOException ex) 
    {
    ex.printStackTrace();
    }

尝试在外部声明 BufferReadertry

BufferedReader br = null;

然后您的 while 循环仅用于打印变量的值。在此期间包含以下 if else 条件,然后尝试以下代码。

while ((sCurrentval = br.readLine()) != null)
            {
                System.out.println("Reading from File " + sCurrentval);
                if (sCurrentval != null && !sCurrentval.trim().isEmpty())
                {
                    try
                    {
                        val = Integer.parseInt(sCurrentval.trim());
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    System.out.println("Reading Value  null ");
                }
            }
于 2013-08-27T09:58:04.180 回答