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

前端 未结 8 1177
无人及你
无人及你 2020-11-21 23:48

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

相关标签:
8条回答
  • 2020-11-22 00:25

    This may not be what you are looking for, but in the interest of coming at a problem from another angle....

    Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.

    0 讨论(0)
  • 2020-11-22 00:25

    Below is a sample snippet code to lock a file until it's process is done by JVM.

     public static void main(String[] args) throws InterruptedException {
        File file = new File(FILE_FULL_PATH_NAME);
        RandomAccessFile in = null;
        try {
            in = new RandomAccessFile(file, "rw");
            FileLock lock = in.getChannel().lock();
            try {
    
                while (in.read() != -1) {
                    System.out.println(in.readLine());
                }
            } finally {
                lock.release();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:39

    use java.nio.channels.FileLock in conjunction with java.nio.channels.FileChannel

    0 讨论(0)
  • 2020-11-22 00:42

    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.)

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

    0 讨论(0)
  • 2020-11-22 00:43

    Don't use the classes in thejava.io package, instead use the java.nio package . The latter has a FileLock class. You can apply a lock to a FileChannel.

     try {
            // Get a file channel for the file
            File file = new File("filename");
            FileChannel channel = new RandomAccessFile(file, "rw").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();
    
            /*
               use channel.lock OR channel.tryLock();
            */
    
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            try {
                lock = channel.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }
    
            // Release the lock - if it is not null!
            if( lock != null ) {
                lock.release();
            }
    
            // Close the file
            channel.close();
        } catch (Exception e) {
        }
    
    0 讨论(0)
  • 2020-11-22 00:43

    Use this for unix if you are transferring using winscp or ftp:

    public static void isFileReady(File entry) throws Exception {
            long realFileSize = entry.length();
            long currentFileSize = 0;
            do {
                try (FileInputStream fis = new FileInputStream(entry);) {
                    currentFileSize = 0;
                    while (fis.available() > 0) {
                        byte[] b = new byte[1024];
                        int nResult = fis.read(b);
                        currentFileSize += nResult;
                        if (nResult == -1)
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
            } while (currentFileSize != realFileSize);
        }
    
    0 讨论(0)
提交回复
热议问题