1

在我的应用程序中,我将检查之前是否生成了唯一 ID,如果没有,它将生成一个并将其写入文件。但是在多进程应用程序中,当多个进程尝试写入同一个文件时,如果它们都发现之前没有生成任何 uid,就会感觉有问题。

那么在android中,如何防止多个进程写入同一个文件呢?

4

1 回答 1

2

在 android 中,您可以使用 FileLock 锁定文件以防止另一个进程写入该文件。

文件锁可以是:独占或共享

Shared :多个进程可以在单个文件的同一区域上持有共享锁。

Exclusive:只有一个进程可以持有独占锁。没有其他进程可以同时持有与独占重叠的共享锁。

final boolean isShared() : check wheather the file lock is shared or exclusive.

final long position() : lock's starting position in the file is returned.

abstract void release() : releases the lock on the file.

final long size() : returns length of the file that is locked.

以下示例将消除您对如何锁定文件并在对其执行操作后释放它的疑问。

 public void testMethod() throws IOException,NullPointerException{

    String fileName="textFile.txt";
    String fileBody="write this string to the file";
    File root;
    File textFile=null;
    //create one file inside /sdcard/directoryName/
    try
    {
        root = new File(Environment.getExternalStorageDirectory(),"directoryName");
        if (!root.exists()) {
            root.mkdirs();
        }
        textFile = new File(root, fileName);
        FileWriter writer = new FileWriter(textFile);
        writer.append(fileBody);
        writer.flush();
        writer.close();
        System.out.println("file is created and saved");
    }
    catch(IOException e)
    {
        e.printStackTrace();

    }
    //file created. Now take lock on the file
    RandomAccessFile rFile=new RandomAccessFile(textFile,"rw");
    FileChannel fc = rFile.getChannel();


    FileLock lock = fc.lock(10,20, false);
    System.out.println("got the lock");

    //wait for some time and release the lock
    try { Thread.sleep(4000); } catch (InterruptedException e) {}


    lock.release();
    System.out.println("released ");

    rFile.close();
}
于 2015-04-17T09:42:06.607 回答