views:

65

answers:

4

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.

+1  A: 

Just a guess, actually -- but I might try combining the two conditions:

   while ((s = br.readLine()) != null && count < 100)
      System.out.println(s + " [line: "+(count++)+"]");

Perhaps?

Joe
Won't that print 101 lines?
johnbk
yes; updated :)
Joe
+2  A: 

You need to combine your while conditions

while (count < 100 && (s = br.readLine()) != null) { ...

(EDIT: as johnbk mentions the count check should be < 100)

irishbuzz
A: 

You don't want to use nested while loops, you want something like

while(count < 101 && (s = br.readLine()) != null){

This will stop the file reading once the count has been reached.

Michael McGowan
+1  A: 

well, your inner loop is running till the end of file..you have to capture both the conditions and by the way you are trying to print 101 lines, not 100. To print 100 lines you need to check for c < 100 since count is initialized to '0'

while ( count < 100  && (s = br.readLine()) != null) {
   System.out.println(s);
   count++;
  }
johnbk
You're correct `count < 100` should be used and your code will correctly print 100 lines. However you should swap the order of the conditions. Otherwise after the 100th line is printed another line will be read from the file before we discover the count has reached it's limit.
irishbuzz
@irishbuzz - Thanks..! I updated the order of conditions
johnbk