• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

seek method in RandomAccessFile

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 897
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, yeah, that makes sence. Thanks alot.
reply
    Bookmark Topic Watch Topic
  • New Topic