Reputation: 715
I got Null pointer exception when reading data from file.if its returning a junk value how to handle that. if i didn't give trim giving some junk value. My code is:
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();
}
}
Upvotes: 0
Views: 188
Reputation: 8466
Your BufferedReader br = null;
with in the try
. But your finally
also using the same variable 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 to declare the BufferReader outside the try
BufferedReader br = null;
And then your while loop is only for the printing the value of the variable. Include the below if else condition within the while and then try the below code.
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 ");
}
}
Upvotes: 1