How can I lock a file using java (if possible)

2018-12-31 04:09发布

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.

标签: java file-io
11条回答
浮光初槿花落
2楼-- · 2018-12-31 04:22

You an use java.nio.* APIs for locking a file. However that doesn't guarantee locking, It depends on if the underlying OS supports locking or not. As I understand Operating systems like Linux doens't support locking and hence you cannot lock even if you use these APIs

查看更多
余生无你
3楼-- · 2018-12-31 04:25

Use a RandomAccessFile, get it's channel, then call lock(). The channel provided by input or output streams does not have sufficient privileges to lock properly. Be sure to call unlock() in the finally block (closing the file doesn't necessarily release the lock).

查看更多
若你有天会懂
5楼-- · 2018-12-31 04:29
package tips.javabeat.nio.lock;  

import java.io.*;  
import java.nio.channels.FileChannel;  
import java.nio.channels.FileLock;  

public class FileLockTest {  

    public static void main(String[] args) throws Exception {  

       RandomAccessFile file = null;  

         FileLock fileLock = null;  

         try 

         {  

             file = new RandomAccessFile("FileToBeLocked", "rw");  

             FileChannel fileChannel = file.getChannel();  



             fileLock = fileChannel.tryLock();  

             if (fileLock != null){  

                 System.out.println("File is locked");  

                 accessTheLockedFile();  

             }  

         }finally{  

             if (fileLock != null){  

                 fileLock.release();  

             }  

         }  

     }  



     static void accessTheLockedFile(){  

        try{  

         FileInputStream input = new FileInputStream("FileToBeLocked");  

          int data = input.read();  

            System.out.println(data);  

      }catch (Exception exception){  

             exception.printStackTrace();  
        }  

     }  
查看更多
骚的不知所云
6楼-- · 2018-12-31 04:35

I found the same issue some years back when I wrote an application that required multiple users on MacOS/Windows to share the same data in multiple files. File locking didn't work on MacOS so I created my own 'ioFile' class which maintained it's own register of file access - open r/o, open r/w, etc, and who 'owned' the lock. This is the only way at the time I could control access from different users on different machines using different OS's.

查看更多
登录 后发表回答