从文件读取数据时我得到Null指针异常。如果它返回一个垃圾值,如何处理它。如果我没有给修剪一些垃圾价值。 我的代码是:
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();
}
}
答案 0 :(得分: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();
}
尝试在try
BufferedReader br = null;
然后你的while循环仅用于打印变量的值。在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 ");
}
}