I am trying to use a file reader and buffered reader in java to print a certain a certain number of lines from a txt file. The file has over 100000 lines, but i just want to print the first 100.
The code i have come up with looks like this:
public class main {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("words.txt");
BufferedReader br = new BufferedReader(fr);
String s;
int count = 0;
while (count <101)
{
while((s = br.readLine()) != null)
{
System.out.println(s);
count++;
System.out.println(count);
}
}
fr.close();
}
}
It prints out something like this:
it
1
was
2
a
3
sunny
4
day
...
and so on (the ints being printed is just so i can see that the counter was incrementing). The trouble is, it goes all the way to the end of the file, rather than stopping after the 100th line of text. My question is, how can i stop it printing after the 100th line?
Thanks in advance.