首頁  >  問答  >  主體

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

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

大家讲道理大家讲道理2686 天前815

全部回覆(2)我來回復

  • phpcn_u1582

    phpcn_u15822017-06-12 09:26:18

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

    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...

    回覆
    0
  • 怪我咯

    怪我咯2017-06-12 09:26:18

    你參考下這個:

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

    回覆
    0
  • 取消回覆