Null Pointer Exception even after a check conditon [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Here is the code:
File tempFile = new File("myTempFile.txt");
tempFile.createNewFile();
File inputFile = new File("Friend_list.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine;
trimmedLine = currentLine.trim();
}
In this part of the code, there is a NullPointerException. The exact exception is mentioned below:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"String.trim()" because "currentLine" is null at com.company.Main.delete(Main.java:167)
at com.company.Main.main(Main.java:48)
The question is if the string is null then how could it enter the while loop? I cross checked the file, data is there in the file then how could it be null?

I think that this is the actual cause of your problem. (Based on the code that you inappropriately posted as an "answer" - now deleted.)
currentLine = reader.readLine();
trimmedLine = currentLine.trim();
Note that in >>those<< statements, you are NOT testing for null before calling trim().
The code in your question is not the code that causes the problem
Your diagnosis was problematic because (presumably) you didn't pay attention to the line numbers in the stacktrace.

Related

Reading from file to array but last line overrides all other lines [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
So I wanted this to be my last resort because I did enough progress with doing the main code and I was only to come here if nothing else worked.
String line = "";
try
{
BufferedReader br = new BufferedReader (new FileReader("league.txt"));
FootballClub club = new FootballClub();
while ( ( line = br.readLine() ) != null )
{
String[] FC = line.split(",");
club.setName(FC[0]);
club.setLocation(FC[1]);
club.setMatchesPlayed(Integer.parseInt(FC[2]));
club.setWins(Integer.parseInt(FC[3]));
club.setDraws(Integer.parseInt(FC[4]));
club.setLosses(Integer.parseInt(FC[5]));
club.setGoalsScored(Integer.parseInt(FC[6]));
club.setGoalsAgainst(Integer.parseInt(FC[7]));
club.setGoalDifference(Integer.parseInt(FC[8]));
club.setPoints(Integer.parseInt(FC[9]));
league.add(club);
}
br.close();
}
catch (FileNotFoundException e) { }
catch (IOException e){ }
This is my code from reading from a text file into array. The text file is as follows:
Chelsea,London,0,0,0,0,0,0,0,0
WestHam,London,0,0,0,0,0,0,0,0
The problem is that when I test the program, two clubs get added to the array however the values for the first line get overridden by the second line. I have been trying to get one line added first then the second until there is no line but I seem to be lucking out. I have been looking everywhere to try and fix it but no luck and it does seem like an easy fix but I'm burned out and can't find it. Any pointers and suggestions would be appreciated.
You need to create a new instance of the class on each iteration, otherwise you keep setting properties on the same object, so only the last line will be stored.
while ((line = br.readLine()) != null){
String[] FC = line.split(",");
FootballClub club = new FootballClub();
//...
}

i am getting a null-pointer at resource.length() and i am not able to figure it out why? even though the the file has data [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
class WordCount
{
String resource;
void read () throws IOException
{
File file = new File("C:\\Users\\Desktop\\read.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((resource = br.readLine()) != null)
{
resource.trim();
}
System.out.println(resource.length());
br.close();
}
}
Here you are assigning null at final step of loop:
while ((resource = br.readLine()) != null)

BufferedWriter throwing NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to write a value fetched from a hashmap into a file :
public writeToFile(HapshMap<String,String> , String fileName) {
File myFile = new File(filePath);
BufferedWriter bufferedWriter = null;
Writer writer = new FileWriter(myFile,false);
bufferedWriter = new BufferedWriter(writer);
String paramsValue = params.get("NAME");
bufferedWriter.write(paramsValue);
}
In the above code , the key "NAME" is not there in the HashMap.
And it is throwing NPE .Can anyone suggest what can be done and why is NPE getting thrown?
BufferedWriter does throw an NPE when you ask it to write null somewhere.
That is a situation you will have to know about and deal with. For example, replace null value with some well known string that indicates emptiness:
Object nvl(Object value, Object defaultValue) {
return value != null ? value : defaultValue;
}
<...>
String value = nvl(map.get("Name"), ""); // using empty string instead of null
writer.write(value);

Problems with flush and printwriter [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have the following code:
while (true) {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String result = null;
while (result != "string") {
out.println("string one");
out.flush();
String var = null;
if ((var = in.readLine()) != null) {
var2 = function(login);
out.println(var2);
out.flush();
}
}
}
The flushing is not working correctly, mainly the first iteration of the outer while loop will print both outputs, but then after that there is an odd delay and everything is messed up ("string one" is not printing to the output).
What am I doing wrong?
You are using != tocompare String references which isn't going to do what you thinks, though it doesn't matter because you never change anyway.
Most likely you have a bug at the other end which is why readLine() blocks waiting for some text.

How to fix BufferReader issue in java [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
Its been a while since I did Java and so am going through a book. As far as I can see the following code is correct however I am having trouble compiling it. I used to use Scanner, but this book is taking this approach, and I would prefer to follow it and do the exercises as explained, can anyone see what is wrong here?
import java.io.*;
class ReadFile
{
public static void main( String[] args )
{
try
{
FileReader file = new FileReader("Sheffield.data");
}
catch (IOException e)
{
System.out.println("A read error has ocurred" );
}
BufferedReader buffer = new BufferedReader(file);
String line = "";
while ((line = buffer.readLine()) != null)
{
System.out.println(line);
}
buffer.close();
}
}
The error I am getting in Windows cmd is as follows:
Simple error I know, any help will be much appreciated.
FIXED!!
BufferedReader buffer = new BufferedReader(file);
String line = "";
while ((line = buffer.readLine()) != null)
{
System.out.println(line);
}
buffer.close();
the above should all be placed in the try statement under the FileReader file = new FileReader("Sheffield.data");
file variable is created in the try block and thus BufferedReader buffer = new BufferedReader(file); doesnt have access to it. Create the reference before try and instantiate in th try block.

Categories