• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile question

 
Archana Agrawal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,
This is the question from the javacaps .

17. 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();
}
}
[a] 123456
[b] 7890
[c] 1000000
[d] .0001
the answer given is b.7890
I know the concept of randomaccessfile,but i am not getting why this is the output.
please help,
archana sunarcha@yahoo.com
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first write writes out one byte of data, representing the boolean value true. The next write writes out 4 bytes of data for the int, 123456. The next write writes out 4 more bytes of data for the value 7890. This behavior continues.
When we perform the seek, we seek past the first 5 bytes (the boolean and the first int) and read the bytes 6-9. These 4 bytes contain the value 7890.
That's why we get that value. What are you confused about?
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic