io - java 文件操作,如何向指定的位置插入內容 (不是替換內容) ?
問題描述
java 文件操作,如何向指定的位置插入內容 (不是替換內容) ?
問題解答
回答1:不存在真正意義上的插入文件,因為文件大小是確定的。所以只能用臨時文件去替換源文件。
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...
回答2:你參考下這個:
https://faceghost.com/questio...
