您的位置:首页技术文章
文章详情页

io - java 文件操作,如何向指定的位置插入内容 (不是替换内容) ?

【字号: 日期:2023-11-08 14:55:15浏览:51作者:猪猪

问题描述

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

标签: java