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 halpsplitted String:
I
am
pretty
stupid.
haha
idk
Exception in thread
"main" java.lang.NullPointerException
at txt_counter.main(txt_counter.java:32)