为什么 BufferedWriter 没有通过打开的 FileChannel 写入文件?

Why BufferedWriter is not writing into the file over the opened FileChannel?

下面是我的代码。我能够成功读取文件。但无法使用 BufferedWriter 将替换后的内容重新写入其中。但是可以用 ByteBuffer 来做。请在我出错的地方提出任何建议。

myFile.txt内容:

Key1-Value1
Key2-Value2
Key3-Value3

Java 代码如下:

String fileAbsolutePath = "C:\myPath\myFile.txt";

        try {
            RandomAccessFile file = new RandomAccessFile(fileAbsolutePath, "rw");
            FileChannel fileChannel = file.getChannel();
            FileLock lock = fileChannel.lock();
            // read from the channel
            BufferedReader bufferedReader = new BufferedReader(Channels.newReader(fileChannel, "UTF-8"));
        List<String> filteredList = bufferedReader.lines().filter(line -> !line.contains("KEY1-VALUE1")).onClose(() -> {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }).collect(Collectors.toList());
            fileChannel.truncate(0);
            BufferedWriter bufferedWriter = new BufferedWriter(Channels.newWriter(fileChannel, "UTF-8"));
            for (String string : list) {
                bufferedWriter.write(string);//does n't work
                bufferedWriter.newLine();
            }
            lock.release();
            file.close();
            fileChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

有效的 ByteBuffer 部分:

ByteBuffer buff = null;
            for (int i = 0; i < filteredList.size(); i++) {
                buff = ByteBuffer.wrap(filteredList.get(i).concat("\n").getBytes(StandardCharsets.UTF_8));
                fileChannel.write(buff);
            }

挑战是在 BufferedWriter

的帮助下实现同样的目标

尝试 try-with-resources 后更新了代码

try (RandomAccessFile file = new RandomAccessFile(fileAbsolutePath, "rw");
                FileChannel fileChannel = file.getChannel();
                FileLock lock = fileChannel.lock();
                BufferedReader bufferedReader = new BufferedReader(Channels.newReader(fileChannel, "UTF-8"));
                BufferedWriter bufferedWriter = new BufferedWriter(Channels.newWriter(fileChannel, "UTF-8"))) {

            // read from the channel
            List<String> list = bufferedReader.lines().filter(line -> !line.contains("Key1-Value1"))
                    .collect(Collectors.toList());
            fileChannel.truncate(0);
            list.forEach(item -> {
                try {
                    bufferedWriter.write(item.concat("\n"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            bufferedWriter.flush();
        }

您没有在最后刷新 BufferedWriter,这意味着它包含您希望写回的部分或全部行。在关闭通道之前添加一个 flush() 以确保写出缓冲区:

bufferedWriter.flush();
lock.release();

理想情况下,您应该将 try() 与资源一起使用,以便在适当的时候彻底关闭所有文件。