通过Java将文本插入到现有文件中 [英] Inserting text into an existing file via Java

查看:92
本文介绍了通过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆