Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Last line  RSS feed

 
jacq carballo
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jacq carballo
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!