hi, I wanted a better way of reading a file. I am having a flat file with the header and trailer information. Before I can read the contents of the file, I want to read the trailer information for some validations. I can use an input stream to read the file. but since there are more than 100000 lines between the header and trailer it would take time to reach the last of the file for the trailer information. if the validations for the trailer are not satisfied, then there is no point reading the whole file. RandomAccessFile can be used to read the file. But, I was wondering if there was any other better way to read the file. Any suggestions in this matter will be of great help. Thanks and regards, Sudha
Hi, In my opinion, you could use RandomAccessFile and seek method or use FileReader to read and skip method if you know the length of the tailer info. Something like skip (fileLength - trailerLength) and read the tailer but it still required reading the file once. -Dhanush
RandomAccessFile might be great if the trailer is always exactly the same length, like 100 bytes. Then you could seek to file length minus 100 and always hit the first byte of the trailer. You might run into trouble with subtle differences between Windows and Unix line feeds and end of file ... if you're not sure where the file was last edited it may or may not have a couple extra bytes. Be sure to test with both!
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Right now I am using RandomAccessFile, but I wanted to know if there was a better and optimal way of reading this kind of flat files. Thank you Dhanush and Stan for your advice. Stan, I shall surely try on a Unix and Windows machine. Guys, do let me know if you find out a better way. Thanks again.
Take a look at java.nio.channels.FileChannel set the position to be read from by aFileChannel.position(long) and read by aFileChannel.read(ByteBuffer) Can you test it and tell us whether it reads the whole file before going to the specified position?
Hi Jose, The problem is that I am using java libraries V1.2 and not the latest. So I do not have the liberty of choosing classes from java.nio. I shall anyways try it out when I get a chance. Thanks anyways. regards, Sudha
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.