BufferedReader methods

I am trying to find out how many lines of code I have in a txt document before I process it. I made a Bufferedreader, then wrote

br.mark() to mark the stream

then I run a loop to find out how many lines there are.

br.reset() I use to return the stream to the beginning. HOwever, my code seems to just stop after that line. I put a System.out.print(...) line after it, and nothing happens.

br = new BufferedReader(new FileReader(filename));

br.mark(4000);

int lines = 0;

while (br.readLine() != null){

lines++;

}

br.reset();

System.out.print(lines);

System.out.print(br.readLIne().toString());

[674 byte] By [snoboardera] at [2007-11-26 14:53:12]
# 1
> I am trying to find out how many lines of code I have> in a txt document before I process it. Stop right there. Why? This means you have to read the file twice. A non-scalable solution.
ejpa at 2007-7-8 8:41:30 > top of Java-index,Java Essentials,Java Programming...
# 2
mostly because If I do a while loop that says while( br.readLine() != null)and then try to use br.readLine() in the loop, it will skip lines in the txt document
snoboardera at 2007-7-8 8:41:30 > top of Java-index,Java Essentials,Java Programming...
# 3

I'm not totally sure of this, but I know that not all input streams are actually required to support mark and reset, and I suspect that buffered reader is one of them, due to the nature of how it works.

If you really must do it this way, as you read the data, store it somewhere else that will allow you to go and retrieve the data again later...

OR

Re-open the buffered reader (and of the course, the file) after you've determined how many lines there are.

However, the other posters are right, this is a bit strange, because it's not very efficient nor is it very scalable.

Maybe try looking at other streams or reader, of especially, try looking at the NIO package, which gives you direct control and access to the data, allowing you to revisit where you started from time and time again.

- Adam

guitar_man_Fa at 2007-7-8 8:41:30 > top of Java-index,Java Essentials,Java Programming...
# 4

> mostly because If I do a while loop that says

> while( br.readLine() != null)

> and then try to use br.readLine() in the loop, it

> will skip lines in the txt document

'It' isn't skipping any lines, you are doing that to yourself.

String line;

while ((line = in.readLine()) != null)

{

// do stuff

}

ejpa at 2007-7-8 8:41:30 > top of Java-index,Java Essentials,Java Programming...