• 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

JQ+ question RandomAccessFile help.....

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic