【问题标题】:Append text at the beginning of a file without deleting the file [duplicate]在文件开头附加文本而不删除文件[重复]
【发布时间】:2014-05-27 09:52:49
【问题描述】:

有很多关于此的帖子,但我找不到一个正常工作例如下面的代码有效,但它删除了第一行。

我想在文件的开头插入一些文本而不删除任何内容,只是插入。这可能吗?

RandomAccessFile f = new RandomAccessFile(new File("myFile.txt"), "rw");
f.seek(0);
f.write("Blah Blah This is first line".getBytes());
f.close();

我也试过this,还是删除了前12个字节

【问题讨论】:

  • 使用您发布的代码,但首先阅读该行并将其添加到您正在插入的文本中,然后再将其写回文件
  • @Hrqls tnx Coudl 你可以在一个例子中简单地展示一下吗?

标签: java


【解决方案1】:

伪代码是

String existing = Read whole content of file. 

String newcontent = "Blah Blah This is first line" + existing

f.write(newcontent);      

【讨论】:

  • 是的。文件系统通常不支持在文件之间或文件开头插入数据。不过支持追加到末尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 2016-12-05
  • 2013-04-28
  • 2020-05-21
相关资源
最近更新 更多