aspose file tools*
The moose likes I/O and Streams and the fly likes RandomAccessFile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "RandomAccessFile" Watch "RandomAccessFile" New topic
Author

RandomAccessFile

Prashant Sehgal
Ranch Hand

Joined: Jun 20, 2003
Posts: 56
Although we can seek N bytes in a RandomAccessFile and read/write at the N+1 bytes, can we also do the same with lines? Can we skip the N lines and read/write directly at the (N+1)th line?

I know we can use the readLine() method and keep a count of how many lines we have read, uptill the point count reaches N. But then that's not really Random Access, is it?

How can say something like raf.seekLine(100) and directly reach the 100th line?

Is there a way?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
No - because in order to know how many lines there are, something needs to look at each character along the way to see if it's a \r or \n. Without knowing where each line boundary is, there's no way to know what the line count is, or where each line begins. You could write a class which does this work for you, making it look like you're getting random access, but you still need to read all the bytes up to line n, at least once.


"I'm not back." - Bill Harding, Twister
Prashant Sehgal
Ranch Hand

Joined: Jun 20, 2003
Posts: 56
Hmm.

I built myself a custom class that indexes the new lines in a file according to byte position.

Just call and it returns a long that gives the byte position of that line in the file. Then you can use your RandomAccessFile object to seek that byte position. Here's the code for ByteInderxer:


[ May 14, 2004: Message edited by: Prashant Sehgal ]
 
Don't get me started about those stupid light bulbs.
 
subject: RandomAccessFile
 
Similar Threads
update mode in file handling
trying to use a txt file like a database
B&S: Writing to the db file
RE:queries in files
Reading and Writing from Large File, OutOfMemory