用Java读取和处理文件时如何防止文件被覆盖?

发布于 2024-08-01 23:40:18 字数 167 浏览 1 评论 0原文

我需要使用 Java 读取和处理一些大文件,我想知道是否有某种合理的方法来保护该文件,使其在我读取和处理时不会被其他进程覆盖。 加工吗?

也就是说,可以通过某种方式使其只读、保持“打开”或其他方式...

这将在 Windows 环境中完成。

br, 灯子

I'd need to read and process somewhat large file with Java and I'd like to know, if there is some sensible way to protect the file that it wouldn't be overwritten by other processes while I'm reading & processing it?

That is, some way to make it read-only, keep it "open" or something...

This would be done in Windows environment.

br,
Touko

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新人笑 2024-08-08 23:40:18

你想要一个FileLock

FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel();

// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock = channel.tryLock();

// ...  

// release it
lock.release();

为了简单起见,我省略了一个封闭的 try/finally 块,但你不应该在你的生产代码中

you want a FileLock:

FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel();

// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock = channel.tryLock();

// ...  

// release it
lock.release();

for simplicity's sake I've omitted an enclosng try/finally block but you shouldn't in your production code

尤怨 2024-08-08 23:40:18

工作大部分正常,有一些问题:因为锁定不似乎是完全绝对的

Working mostly fine, got some issues : as the locking doesn't seem to be totally absolute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文