Des C
Des C

Reputation: 61

Counting Words and Newlines In A File Using Java?

I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.

For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:

FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;

int lines = 1;

while ((strLine = buffRead.readLine()) != null)
{
    if(strLine.contains(newLines))
    {
        System.out.println("Line Found");
        lines++;
    }
}
System.out.println("Total Number Of Lines In File: " + lines);

This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.

Would anyone happen to know the reason why the above code does not work?

Upvotes: 0

Views: 368

Answers (2)

Robert
Robert

Reputation: 6540

readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))

Upvotes: 0

Andrew White
Andrew White

Reputation: 53496

Read the javadocs for readLine.

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Upvotes: 3

Related Questions