0

I am trying to make a Java program that counts the words and the lines in an '*.txt' - file. So far so good. The code works only if the '.txt' has only 2 lines. If put more lines into it I get a NullPointerException at the .split(" "); part in my code. I have read somewhere that could be something with .readLine()-function. But I have really no clue what really causes it.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class txt_counter {
static String FilePath = "C:\\Users\\diasc\\Desktop\\test.txt";

public static void main(String[] args) throws IOException{
    FileReader finput = null;
    BufferedReader binput = null;

    try {
        finput = new FileReader(FilePath);

        System.out.println("Orignal txt output:");
        int a;
        while ((a = finput.read()) != -1) {
            System.out.print((char) a);   
         }

         binput = new BufferedReader(new FileReader(FilePath));
         int Zcount = 1;
         int Wcount = 1;
         while ( binput.readLine() != null ) {
            String[] woerter = binput.readLine().replaceAll("\\s+", " ").split(" ");
            System.out.println("\n\nsplitted String: ");
            for(int i =0; i<woerter.length; i++)
            {
                System.out.println(woerter[i]);
            }
            Wcount = Wcount + woerter.length;
            Zcount++;
         }
         System.out.println("\nLines: " + Zcount);
         System.out.println("Words: " + Wcount);

    }finally {
         if (finput != null) {
             finput.close();
         }
         if(binput != null) {
             binput.close();
         }
    }
}

Console Output:

Orignal txt output: lol
I am pretty stupid. haha idk
send halp

splitted String:
I
am
pretty
stupid.
haha
idk
Exception in thread
"main" java.lang.NullPointerException
at txt_counter.main(txt_counter.java:32)

Destro
  • 27
  • 6

1 Answers1

1

In your while loop you read a line from the buffered reader and compare it to null but the line is then never used. In the body of the while loop you then read the next line without checking if the result is null. The usual way of reading a file line by line is like this:

String line;
while ((line = binput.readLine()) != null) {
  String[] woerter = line.replaceAll("\\s+", " ").split(" ");
  ...