天天看点

java access插入_通过Java将文本插入现有文件

java access插入_通过Java将文本插入现有文件

暮色呼如

好的,这个问题已经很老了,但是FileChannels自Java 1.4起就存在了,我不知道为什么在替换或插入文件内容的问题上没有提到它们。FileChannel很快,请使用它们。这是一个示例(忽略异常和其他内容):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();}