Click to See Complete Forum and Search --> : Reading the Last Line of a File


Ximvu
06-23-2005, 04:14 PM
Does anyone know if there's a way to read the last line of a file? I'm writing a Java application that reads in a text file that looks something like...

1 dog 56 73 287 9.54
2 cat 32 10 984 2.45
...

The first number in the line is an index number, and these files can be anywhere from 2,000 to 10,000 lines long. I'd like to read in the index number of the last line so I can find out how many categories I'm working with and set up some arrays. If it isn't possible, I can always use ArrayLists, or just read through the entire file to get to the last line, but it seems like there should be some way to jump there...maybe I just have wishful thinking.

buntine
06-23-2005, 04:46 PM
You pretty much have to read through the contents of the file. Even if you call a pre-built method, it wil still have to read through the file to get to a specified point.

Take a look at the LineNumberReader class. It will not be resource hungry or slow if your file is less than about 20,000 lines. Just read through each line and then use getLineNumber().

Regards.

buntine
06-23-2005, 04:47 PM
Here is a direct link: http://java.sun.com/j2se/1.4.2/docs/api/java/io/LineNumberReader.html

chong
06-24-2005, 01:28 AM
perhaps u can consider write a C function that does the reverse reading(read from filesize bytes backwards till a newline character) , then port to java.

Karthikeyan
06-24-2005, 05:47 AM
Why don't you maitain the last ( record ) index number in a separate file... ?

buntine
06-24-2005, 05:56 AM
Or you could store the amount of lines as a numeric value on the first line of the file and then increment it as new data is added.

Regards.

Ximvu
06-24-2005, 08:49 PM
Hey thanks, the LineNumberReader sounds quite useful actually, I hadn't seen it before. However, I'm liking the idea of putting the total index on the first line, I'll probaly just stick with that. Thanks again for the ideas.

buntine
06-24-2005, 08:59 PM
No worries. ;)