Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile not erasing contents of old file  RSS feed

 
Raja Kannappan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am creating a "testfile" using RandomAccessFile like this:

RandomAccessFile raf = new RandomAccessFile("testfile", "rw");
raf.writeInt(2);
raf.writeChar('f');
raf.seek(0);
System.out.println(raf.readInt());
System.out.println(raf.readChar());
raf.close();

When I ran first time, it created the file with 2 and f and printed properly. Next time, I commented line no. 3 (i.e no writeChar('f')) and ran the program again and again it printed 2 and f. I looked at the file and it had f in there.

I was assuming that everytime the contents would be erased and re-written again. But it seems like it only overwriting the affected bytes and keeping other bytes intact. Is this the way it is supposed to behave? Is there a way to complete erase and re-write the file again?

Thanks,

- Raja.
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this behavior is normal...

Try using setLength(0) to truncate the file.
 
Raja Kannappan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That works. Thanks.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!