如何使用 java 锁定文件(如果可能) [英] How can I lock a file using java (if possible)

查看:21
本文介绍了如何使用 java 锁定文件(如果可能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 FileReader 打开文件的 Java 进程.如何防止另一个(Java)进程打开这个文件,或者至少通知第二个进程该文件已经打开?如果文件已打开(这解决了我的问题),这是否会自动使第二个进程出现异常,或者我是否必须在第一个进程中使用某种标志或参数显式打开它?

I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?

我有一个 Java 应用程序,它列出了一个文件夹并打开列表中的每个文件进行处理.它一个接一个地处理每个文件.每个文件的处理包括读取它并根据内容进行一些计算,大约需要 2 分钟.我还有另一个 Java 应用程序,它执行相同的操作,而是写入文件.我想要的是能够同时运行这些应用程序,所以场景是这样的.ReadApp 列出文件夹并找到文件 A、B、C.它打开文件 A 并开始读取.WriteApp 列出文件夹并找到文件 A、B、C.它打开文件 A,看到它是打开的(通过异常或任何方式)并转到文件 B.ReadApp 完成文件 A 并继续到 B.它看到它是打开的并继续到 C.当 ReadApp 正在读取同一个文件时,WriteApp 不写入是至关重要的,反之亦然.它们是不同的过程.

I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.

推荐答案

FileChannel.lock 可能就是你想要的.

FileChannel.lock is probably what you want.

try (
    FileInputStream in = new FileInputStream(file);
    java.nio.channels.FileLock lock = in.getChannel().lock();
    Reader reader = new InputStreamReader(in, charset)
) {
    ...
}

(免责声明:代码未编译,当然也未测试.)

(Disclaimer: Code not compiled and certainly not tested.)

请注意 FileLock 的 API 文档.

这篇关于如何使用 java 锁定文件(如果可能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆