Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JQ+ question RandomAccessFile help.....

 
Rowan Chattaway
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of the following code segments will correctly write the text "FINAL TEXT" to the end of a file "file.txt ?
1. RandomAccessFile raf = new RandomAccessFile("file.txt", "a");
raf.writeChars("FINAL TEXT");
2. RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.writeChars("FINAL TEXT");
3. RandomAccessFile raf = new RandomAccessFile("file.txt", "a");
raf.seek( raf.length() );
raf.writeChars("FINAL TEXT");
4. RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek( raf.length() );
raf.writeChars("FINAL TEXT");
5. RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek( raf.length() - 1);
raf.writeChars("FINAL TEXT");
The correct answer is apparently 4)
However, I'm sure I've read that raf.length() - 1) will point to the end of the file in RHE...........then then I haven't slept in 48 hours so I may just be delirious..........
Any help would be much appreciated,
Rowan.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(raf.length() - 1) is the position of the last character in the file. If you write to this position, you will overwrite the character that was previously last with a "F". If you want to write the string after all existing text, you need to position the file pointer after the last character.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic