我怎样才能锁定一个文件使用Java(如果可能的话) [英] How can I lock a file using java (if possible)

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

问题描述

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

澄清:

我有一个Java应用程序列出了一个文件夹并打开列表中的每个文件来处理它。它处理每个文件之后。每个文件的处理包括读取它并根据内容进行一些计算,大约需要2分钟。我也有另一个Java应用程序,做相同的事情,而是写在文件上。我想要的是能够同时运行这些应用程序,所以场景就像这样。 ReadApp列出文件夹并找到文件A,B,C,打开文件A并开始读取。 WriteApp列出文件夹,并找到文件A,B,C。它打开文件A,看到它是打开的(通过例外或任何方式)并进入文件B. ReadApp完成文件A并继续到B.它看到它是开放的,并继续到C.当ReadApp正在读取同一个文件时,WriteApp不写,反之亦然。它们是不同的进程。

解决方案

FileChannel.lock可能是你想要的。

  FileInputStream in = new FileInputStream(file); 
尝试{
java.nio.channels.FileLock lock = in.getChannel()。lock();
尝试{
读取器读取器=新的InputStreamReader(in,charset);
...
} finally {
lock.release();
}
} finally {
in.close();





(免责声明:代码没有编译,当然也没有测试过。)



请注意 FileLock的API文档


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?

To clarify:

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 is probably what you want.

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

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

Note the section entitled "platform dependencies" in the API doc for FileLock.

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

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