Get # of lines in text file

C

Collin VanDyck

Jo said:
How do I get the number of lines in a text file?

Try creating a LineNumberReader and read the entire file line by line and
keep count.
 
J

Jo

Collin VanDyck said:
Try creating a LineNumberReader and read the entire file line by line and
keep count.

I did this but when I use LineNumberReader it seems to make
BufferedReader.readLine() return null. Any ideas how I can "reset" the
BufferedReader so it goes back to the start of the file (and it's not the
reset() method).

If I remove the LineNumberReader() stuff in the while loop then the
BufferedReader works fine.

<code>

public Record[] readScoreboard() throws IOException {
FileReader fr = new FileReader(_scores_file);
BufferedReader br = new BufferedReader(fr);
LineNumberReader lnr = new LineNumberReader(fr);
String str_line;
int line_count = 0;
boolean flag = true;
String str_count;

while (flag) {
str_count = lnr.readLine ();
if (str_count == null) {
flag = false;
}
else {
line_count++;
}
}

//System.out.println("lines: " + line_count);
int t = 0;
int x = 0;
int y = 0;
int m = 0;

for (int i = 1; i <= line_count; i++) {
System.out.println("here");
try {
str_line = br.readLine();
System.out.println(str_line); // this displays "null"

}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(new JDialog(), e.getMessage());
}
}
catch (NullPointerException e) {
//JOptionPane.showMessageDialog(new JDialog(), e.getMessage());
}
}

//input done, so close the stream
br.close();

return _records;
}

</code>
 
C

Chris Smith

Jo said:
I did this but when I use LineNumberReader it seems to make
BufferedReader.readLine() return null. Any ideas how I can "reset" the
BufferedReader so it goes back to the start of the file (and it's not the
reset() method).

A Reader is a one-shot thing. To start over, you need to create a new
FileReader to read from _scores_file.

Incidentally, you're mis-using LineNumberReader. Just do this:

LineNumberReader lnr = new LineNumberReader(
new FileReader(_scores_file));
try
{
lnr.setLineNumber(1);

String line;
while ((line = lnr.readLine()) != null);

line_count = lnr.getLineNumber();
}
finally
{
lnr.close();
}

And then,

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

...

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top