aspose file tools*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Looping over the contents of the file... 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 » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Looping over the contents of the file..." Watch "Looping over the contents of the file..." New topic
Author

Looping over the contents of the file...

Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

Howdy folks,
What would you say is the standard way to loop over the contents of the file?
I do the following but am convinced there is a better way:



Thanks,
Best regards.


SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJD, SCEA/OCMJEA

Live life to an interface, not an implementation!
Mike Ngo
Ranch Hand

Joined: Oct 16, 2006
Posts: 89
why are you looping?
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

To read every row...?
Mike Ngo
Ranch Hand

Joined: Oct 16, 2006
Posts: 89
The RandomAccessFile is used to randomly access any byte in a file so typically you would do something like this

RandomAccessFile stream = // open it
// calculate file pointer
long offset = calculateOffset(my_record);
stream.seek(offset)
// read my record

If you don't need to randomly access the data, you can use DataInput/OutputStream.
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

I see what you mean, but i don't see how you would use RandomAccessFile to read ALL rows? And if the answer is to use a DataInputStream, then how can i read a certain amount of bytes for each field like RandomAccessFile does? How do i read each row with a RandomAccessFile? Or is the trick to mix it with a DataInputStream...?

Kind regards,
Mars.
Mark Smyth
Ranch Hand

Joined: Feb 04, 2004
Posts: 288
Originally posted by Marcelo Ortega:
I see what you mean, but i don't see how you would use RandomAccessFile to read ALL rows? And if the answer is to use a DataInputStream, then how can i read a certain amount of bytes for each field like RandomAccessFile does? How do i read each row with a RandomAccessFile? Or is the trick to mix it with a DataInputStream...?

Kind regards,
Mars.


I think the easyest way is to keep track of how many records (deleted and active) are in the file.

Then you will do something like the following:



To calculate the number of records would be something like:

numrecords= (fileSize - HeaderLength) / recordLength + 1 //Dont forget about active delete flag


SCJP<br />SCJD
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Looping over the contents of the file...
 
Similar Threads
Writing to an already created RandomAccessFile
How to see the contents of jar file?
ObjectInputStream
JavaMail is too verbose
How to use excel file in C program for file handeling?