How do you measure how many line breaks there are in a file with java?

I’m learning Java for my academic studies, anyhow, I keep running into minor issues, like now, I want to know if there’s a way where you can measure how many line breaks there are in a .txt file.

I’ve built a program that reads data in from a .txt file and saves the data to an arraylist, however because I know the current amount of line breaks are in the file, it’s kinda cheating. I’ve just made a loop that iterates through all of the line breaks in the .txt file, btw there are 200. But let’s say I didn’t know there were 200 line breaks, would there be a way to get around this?

So all I did was :

int i = 0;
while(i < 200){
    // Do stuff here
    i++;
}

I know the way I’ve done it now is kinda cheating, but I’d like to write it in a way where it will actually look at the file, look at how many elements or in this case, line breaks there are, then setting the number of line breaks/elements as the comparison to i (or the counter in the loop).

p = Runtime.getRuntime().exec("wc -l " + fileName);
p.waitfor();

:D

That's not helpful. @Argon don't do that. Have a look at this: http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java - This is more how it's done in the real world. Never use exec() unless you have to.

1 Like

Big frown face.

What about..

String readText = readYoTextFile(pth);
Pattern pattern = Pattern.compile("./.\n.");
pattern.matcher(readText);
int count = 0;
while (pattern.find()) {
count++
}

In this situation this is a bad idea. If you just want to read an entire file and perform some actions per line you just use a buffered reader. Regular expressions are slower compared to the reader. Also your code is more complicated. What you want to do is to read a file line by line to do something - so go on and write that.

You need seven lines of code just to do the counting.

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line = br.readLine();
while (line != null) {
    // perform action
}

Using the reader requires five lines of code, is easier to read, does the entire job and the computation takes less time.

Okay, so I've done something like this:

int next = br.read(); // working with int data and string data, anyway....

I thought that next = 200, as there are 200 numeric id's in my .txt file, however it's only = 53?
I can get the loop to work if I do something like

while(i < (next * 4) - 12){
    // do stuff here
}

Anyway, I know this would be an awful way of doing it, but can anyone tell me why next is only 53 when it should be 200.

If it helps at all, the .txt file is laid out like this:

  [int] [String] [String] [int] [int] [int]

I'm sorry if this is getting annoying for anyone, I just want to make sense of why next = 53 and not 200...

Could you please post the first two lines of the file?