0

I need help on the file operation using FileChannel . My requirement is, I have to read a big file from the system, then need to check the file line by line. If certain strings found then need to add new lines or delete old lines from the file. And then need to save the data.

N.B.

  1. I am trying to avoid temp file creation.
  2. Like to do it with FilChannel
  3. Also like to open a single file channel with read and write. To do that I have used RandomAccessFile to get FileChannel.

Please help me on this.

4

1 回答 1

0

如果您想在一个线程中读取多个来源,NIO 会给您带来优势。这样做的代价是更复杂且容易出错的 API。如果您只有一个文件,请使用常规FileInputStream. 据我了解,您正在使用文本文件,因此将流包装为BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(YOUR_FILE)));

下一点是从文件中删除特定的行。这不能“就地”完成,因为文件始终是顺序结构。但是,您可以逐行读取文件并将这些行写入其他文件,而忽略您不想写入的行。然后删除旧文件并重命名您的临时文件。无事可做:频道和随机访问文件都不允许您从文件中间删除信息。

于 2013-05-12T08:12:34.867 回答