gpt4 book ai didi

java - 如何写入/读取已锁定的文件?

转载 作者:行者123 更新时间:2023-12-02 03:23:16 25 4
gpt4 key购买 nike

我正在编写一个线程化的程序,并且可能会跨多个 JVM 运行。锁定文件后(以防止其他进程/线程访问它),我在写入和读取文件时遇到问题。我最初使用的是 FileWriter 但没有将任何内容写入文件。

现在我正在尝试 OutputStream ,由于某种原因,新写入的文件不会追加 - 因此只会出现最后一个条目。我究竟做错了什么?锁定文件后读取/写入文件的最佳方法是什么?

注意:如果我删除所有锁定并将 FileWriterPrintWriter 结合使用,我不会遇到这些问题,所以我认为我的锁定机制错误

try {
// Get a file channel for the file
File file = new File ( path );
RandomAccessFile stream = new RandomAccessFile(file, "rw");
FileChannel channel = stream.getChannel();

// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();

OutputStream os = Channels.newOutputStream(channel);

try (PrintWriter pw = new PrintWriter(os,true)){
System.out.println("Writing " + message);
pw.println(message);
}
os.close();
// Release the lock - if it is not null!
if( lock != null ) {
lock.release();
}
stream.close();
// Close the file
channel.close();

} catch (Exception e) {
}

最佳答案

更简单的解决方案是使用 FileOutputStream

FileOutputStream os = new FileOutputStream(path, true);
FileChannel channel = os.getChannel();
<小时/>

当您使用时

new FileWriter(os, true)

true 表示“附加模式”,但是当您使用时

new PrintWriter(os,true)

true 表示; “刷新换行符”,即它总是会覆盖

当你需要做的就是只从文件末尾写入。我建议你使用

channel.position(channel.size());

在尝试附加之前。

关于java - 如何写入/读取已锁定的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com