This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

seek method in RandomAccessFile

Jo Liang

Joined: Dec 10, 2001
Posts: 11
60. What is the output displayed by the following code?
public class TestIPApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
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,
[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 -
I had some Java certs, but they're too old now...
Jo Liang

Joined: Dec 10, 2001
Posts: 11
Oh, yeah, that makes sence. Thanks alot.
I agree. Here's the link:
subject: seek method in RandomAccessFile
It's not a secret anymore!