0

I try to find a way to write in the first line of a file.

The problem is that I write to the file about 3000 lines (by out.write), but just in the end of this writing I have a information that needed to be insert to the first line of this file.

There is a easy way to do that?

4

2 回答 2

5

There is a easy way to do that?

Nope. This isn't a matter of Java being awkward - it's just file systems, which don't generally allow you to insert data within a file.

Options:

  • Generate the file in memory (3000 lines isn't a lot) and then write it all out when you know the first line
  • Write out the file without the first line, then start a new file by writing out the first line, and then copying the "old" file line by line
  • If you know the length of the first line (in bytes) before you start, you could leave enough room, write out the length of the file, and then overwrite the first line
于 2013-03-30T08:13:15.130 回答
0

You can use two stream, one for your current and one for final. When write end, write information first and then write your current stream to the final stream.

OutputStream finalOs;
OutputStream dataOs;
//...write your data
finalOs.write(your information);
finalOs.write(dataOs);// just 4 example
于 2013-03-30T08:54:25.507 回答