• Post Reply Bookmark Topic Watch Topic
  • New Topic

Find last line number in a file

 
shiva shankar
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I find last number in a file without looping through each file in java ?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, but you can't do that. (Assuming I've correctly guessed what you meant to say here, as opposed to what you actually said.) In order to find the line number, you will need to read each and every byte of the file, at least once. Because you can't possibly know how many lines there are without checking each byte to see if it's a newline. Once you've read each byte once, you might possibly save the results in some manner, such that you won't have to read them again in the future. Unless, of course, the file changes in any way.
[ July 22, 2008: Message edited by: Mike Simmons ]
 
Norm Radder
Bartender
Posts: 1526
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One possible exception would be if ALL the records/lines in the file are exactly the same size/length. Then you could compute the number of lines in the file by dividing the size of the file by the line length.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point. To my mind that feels more like a binary file, and "line number" is irrelevant - we're talking about record number. But yes, it's worth mentioning here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!