为什么bufferedwriter没有通过打开的filechannel写入文件?

u3r8eeie  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(419)

下面是我的代码。我能够成功地读取文件。但无法使用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 (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();
        }
wgmfuz8q

wgmfuz8q1#

您不会在结尾刷新bufferedwriter,这意味着它包含您希望写回的部分或全部行。在关闭通道之前添加flush(),以确保缓冲区已写入:

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

理想情况下,你应该使用 try() 使用资源,以便在适当的时间完全关闭所有文件。

相关问题