문제

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.

도움이 되었습니까?

해결책

NIO gives you advantages if you want to read from several sources in one thread. The price of this is much more complicated and error prone API. If you have only one file use regular FileInputStream. As far as I understand you are working with text file, so wrap stream with BufferedReader:

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

The next point is removing particular lines from the file. This cannot be done "in place" because file is always sequential structure. You can however read the file line-by-line and write the lines to other file ignoring lines that you do not want to write. Then remove old file and rename your temporary file. Nothing to do: neither channels nor random access file do not allow you to remove information from the middle of the file.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top