Search code examples
javaandroidfilelock

How to use FileLock on android?


I think that we are able to lock files for exclusive access as i saw this link: http://developer.android.com/reference/java/nio/channels/FileLock.html

I want to create a save/load a file both in a background process (service) and the real foreground app. They may try to access this file at the same time, in that case one should wait.

I couldn't find a real sample for FileLock on android, i just read many threads that this is not possible on Android. But if so, why the documentation has a section for "FileLock"?


Solution

  • This works on normal Java application:

    File file = ...;
    FileInputStream fis = new FileInputStream(file); // or FileOutputStream fos = new FileOutputStream(file);
    FileLock lock = fis.getChannel().lock(); // or FileLock lock = fos.getChannel().lock();
    
    // do whatever you want with the file
    
    lock.release();