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

Filecontent delete

 
sreejith panampilly
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can delete some content of a file without writing to that file
 
Ådne Brunborg
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sreejith panampilly:
How can delete some content of a file without writing to that file


There are four operations you can do on a file - Create, Read, Update, Delete (CRUD). What you want to do is Update the file, and you cannot do that without writing to it.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
About all you can do is read the whole file, write the parts you like back out to a new file and skip the parts you want to delete. At this point I always drag this out of my rusty old toolbox:

read original
write temp
rename original to backup
rename temp to original
erase backup

That always has a good copy of the original and/or new file in case you kick the plug out of your PC in mid-process.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to delete content from the end of a file, you do have a couple of faster options. You can use RandomAccessFile's setLength() method, or FileChannel's truncate() method, to change the file length to something smaller. This effectively deletes the bytes at the end. If you want to delete content from the beginning or middle, though - for that you really want to do as Stan suggested.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic