开发者

How to write content to a specific location in the file using FileWriter?

I am using Java FileWriter to write a content开发者_运维知识库 into the existing file, but the content is added to the end of the file. I want to add the content at a specific location. Can anyone help me in how to do this?

I am currently doing something like this:

FileWriter fileWriter = new FileWriter(fileW,true);
fileWriter.append(metaData.toString());
fileWriter.flush();
fileWriter.close();


Is your aim to insert data in the middle of a file? If so, most file systems basically don't support this. You need to:

  • Create a new file
  • Copy the first part of your old file to the new file
  • Write your new data to the new file
  • Copy the rest of your old file to the new file
  • Optionally delete/rename the old file and rename the new file so it now appears in the same place as the old file


To write at a specific location guided by the file pointer, you'll have to use the RandomAccessFile class. But messing around with file pointers is a bit hairy so is there any reason why you'd want to write "text" using random access?

A bit more details would help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜