| Author |
Last line
|
jacq carballo
Ranch Hand
Joined: Feb 10, 2002
Posts: 42
|
|
How can you get the last line of the file? I mean i only want to know how many lines are in a file; i don't want to read thru the whole file just to get the last line number. What is the shortest possible code to do this?
|
 |
Maciej Kolodziej
Greenhorn
Joined: Feb 11, 2002
Posts: 26
|
|
|
You have to read the whole file and count newlines (\n). You can do that in a few ways, but cannot avoid it unless all lines have the same length.
|
MK
|
 |
jacq carballo
Ranch Hand
Joined: Feb 10, 2002
Posts: 42
|
|
I would be interested to know the other few ways of knowing the last line number. The file i will be using will have the same length each line. TIA
|
 |
Maciej Kolodziej
Greenhorn
Joined: Feb 11, 2002
Posts: 26
|
|
|
Well, if that's the case, solution is very simple. First check the file size (I don't know if there's a better way, but You can just open FileInputStream and get available() value). Then divide this size by number of characters in line.
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18652
|
|
|
The File class has a method length() to get the number of bytes in a file. This is preferred - the available() method is not guaranteed to return all bytes in the file at once - only those that the system has immediate access to. What if the file is a fragmented disk file? For efficiency the system will let you read bytes from the first fragment before the hard drive has had time to move to the second fragment. This way you can start processing the file right away, rather than waiting for the entire file to be read into a buffer somewhere. (And what if the system buffer is too small? Another reason available() doesn't give you the full size of a file.)
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Last line
|
|
|