• Post Reply Bookmark Topic Watch Topic
  • New Topic

write to the beginning of a file

 
Denis Wang
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I need to open a big file, insert one line at the beginning of it. What is the efficient way to do it?

Thanks.
Denis
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's just not supported by any file system I know (except maybe VM/CMS) or Java IO. You'll probably have to write a new copy of the file. Here's something I drag out for this kind of copying:

while more
read Original
write Temp
end while
rename Original to Backup
rename Temp to Original
erase Backup
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you can achieve this using java.io.RandomAccessFile.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, with RAF you can seek to any spot in the file and overwrite what's there or seek the end and write new stuff at the end, but you can't insert, delete or move bytes around. Copying the file is the only way I know to insert or delete bytes.
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I liked the other sig better, Stan.
You can perform this task with RAF. Append the number of bytes you want to insert to the end of the file. Read data from the old end and write to the new end, shifting the contents down as you work your way up through the file. When you reach the beginning of the file, write the new data.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a very cute solution. I cheerfully stand corrected.

Yeah, "Conway's Law" is not a very sexy sig. I first saw it paraphrased as architecture matches organizational structure and it took me a while to figure out they meant at very large scales, not internal program designs. I'm doing a little more enterprise type work related to integrating a new company, and this rings very true right now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!