io - java 檔案操作,如何在指定的位置插入內容 (不是替換內容) ?
大家讲道理
大家讲道理 2017-06-12 09:24:18
0
2
784

java 檔案操作,如何在指定的位置插入內容 (不是替換內容) ?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(2)
phpcn_u1582

不存在真正意義上的插入文件,因為文件大小是確定的。所以只能用臨時檔案去替換原始檔。

public void insert(String filename, long offset, byte[] content) {
  RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
  RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw");
  long fileSize = r.length();
  FileChannel sourceChannel = r.getChannel();
  FileChannel targetChannel = rtemp.getChannel();
  sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
  sourceChannel.truncate(offset);
  r.seek(offset);
  r.write(content);
  long newOffset = r.getFilePointer();
  targetChannel.position(0L);
  sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
  sourceChannel.close();
  targetChannel.close();
}

https://stackoverflow.com/que...

刘奇

你參考下這個:

https://faceghost.com/questio...

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!