Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile

 
Soum Sark
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for the following question
How many bytes are written into the file after line //1?
(Select one correct answer)
-----------------------------------------------------------------------
import java.io.*;
public class Test049
{
public static void main(String args[])
{
try
{
File f = new File("test.txt");
RandomAccessFile r = new RandomAccessFile(f, "rw");
r.writeChar((char)1);
r.writeInt(2);
r.writeInt(3);
r.seek(4);
r.writeLong(5); //1
}
catch(Exception e)
{
}
}
}

the answer shown is 18 bytes.
But after writing the first char,int,int the total no of bytes written is 2 + 4 + 4 = 10. then we do a seek(4) and then writeLong(5) which is another 8 bytes. What purpose does the seek(4) serve. Doesn't it move the pointer to before the 4th byte and start writing from there so a part of the previous written stuff is erased ??? I am a bit confused with this. Can anyone explain pls
Thanx
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say overwritten rather than erased.
Adding the statement System.out.println(r.length()) results in the output of 12.
So your analysis looks correct.
Where did you find the question?
-Barry
[ August 16, 2002: Message edited by: Barry Gaunt ]
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run this, it produces a file 12 bytes long.
 
Rodge Thomas
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
question is from JIRIS.com mock exam 2, #49 at:
http://www.jiris.com/scjp2/mockexam2answer.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic