通过 Java 将文本插入到现有文件中 [英] Inserting text into an existing file via Java
问题描述
我想创建一个简单的程序(用 Java)来编辑文本文件 - 特别是一个在文本文件中的随机位置插入任意文本片段的程序.此功能是我目前正在编写的更大程序的一部分.
I would like to create a simple program (in Java) which edits text files - particularly one which performs inserting arbitrary pieces of text at random positions in a text file. This feature is part of a larger program I am currently writing.
阅读有关 java.util.RandomAccessFile 的描述,似乎在文件中间执行的任何写操作实际上都会覆盖现有内容.这是我想避免的副作用(如果可能的话).
Reading the description about java.util.RandomAccessFile, it appears that any write operations performed in the middle of a file would actually overwrite the exiting content. This is a side-effect which I would like to avoid (if possible).
有没有简单的方法来实现这一目标?
Is there a simple way to achieve this?
提前致谢.
推荐答案
好吧,这个问题很老了,但是 FileChannels 从 Java 1.4 开始就存在了,我不知道为什么在处理替换或插入文件中的内容.FileChannels 速度很快,请使用它们.
Okay, this question is pretty old, but FileChannels exist since Java 1.4 and I don't know why they aren't mentioned anywhere when dealing with the problem of replacing or inserting content in files. FileChannels are fast, use them.
这是一个例子(忽略异常和其他一些东西):
Here's an example (ignoring exceptions and some other stuff):
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();
}
这篇关于通过 Java 将文本插入到现有文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!