aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes seek method in RandomAccessFile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "seek method in RandomAccessFile" Watch "seek method in RandomAccessFile" New topic
Author

seek method in RandomAccessFile

Jo Liang
Greenhorn

Joined: Dec 10, 2001
Posts: 11
60. What is the output displayed by the following code?
import java.io.*;
public class TestIPApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeInt(7890);
file.writeLong(1000000);
file.writeInt(777);
file.writeFloat(.0001f);
file.seek(5);
System.out.println(file.readInt());
file.close();
}
}
Select correct answer:
A) 123456
B) 7890
C) 1000000
D) .0001
The answer is B. But why?
Thank you very much.
Mark Fletcher
Ranch Hand

Joined: Dec 08, 2001
Posts: 897
Hi Jo,
I think the reason the answer is (b) is due to the use of the seek method on line 12. Seek will position the file pointer at the end of the fifth byte from the beginning of the file. Remember that File I/O is about reading and writing bytes. So in our case
The first value is Boolean 'true' (1 Byte Long)
The next is int '123456'(4 Bytes Long)
So the int '7890' is written starting from the end of byte number 5.
On line 13 you then read the an int at that position using the call to file.readInt(). Recall that int values are 4 bytes long.
Hope that is of help,
Mark
[This message has been edited by Mark Fletcher (edited December 10, 2001).]
[This message has been edited by Mark Fletcher (edited December 10, 2001).]


Mark Fletcher - http://www.markfletcher.org/blog
I had some Java certs, but they're too old now...
Jo Liang
Greenhorn

Joined: Dec 10, 2001
Posts: 11
Oh, yeah, that makes sence. Thanks alot.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: seek method in RandomAccessFile