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