Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

seek method in RandomAccessFile

 
Jo Liang
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 897
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Jo Liang
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, yeah, that makes sence. Thanks alot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic