-2

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?

AKSingh
  • 1,535
  • 1
  • 8
  • 17
  • 3
    If the code is as you have shown us, then `currentLine.trim();` cannot result in an NPE. This suggests that the code is not as you have shown us. Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) ... rather than a code fragment. – Stephen C Jun 18 '21 at 04:19
  • (If the effect that you are seeing is real, then writing a minrep should be a simple thing for you to do. But I suspect that the effect is caused by something else; e.g. not recompiling, looking at the wrong section of your code, etc.) – Stephen C Jun 18 '21 at 04:27
  • I have posted the full code in an answer. please check and help. – NEERAJ yadav Jun 18 '21 at 04:28
  • sir i i am sharing the whole project – NEERAJ yadav Jun 18 '21 at 04:30
  • 1
    The lesson to learn here is: it's hard for us to help you with the code that you don't post. It's important to post a minimal, complete example *that still demonstrates the problem*. (Please don't post huge amounts of irrelevant code, and please don't post code as answers when it's just "here's more code for the question".) – Jon Skeet Jun 18 '21 at 06:02
  • Do not post your code in an answer. Edit your question and include your code. – NomadMaker Jun 18 '21 at 06:27

1 Answers1

0

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().

  1. The code in your question is not the code that causes the problem
  2. Your diagnosis was problematic because (presumably) you didn't pay attention to the line numbers in the stacktrace.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216