【问题标题】:In Android, how to prevent multiple process writing to the same file在Android中,如何防止多个进程写入同一个文件
【发布时间】:2015-04-17 03:37:35
【问题描述】:

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

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

【问题讨论】:

  • 只有一个进程负责这可能是最简单的 - 如果其他人认为需要完成它,他们可以使用 Android 的众多 IPC 机制之一来请求该进程执行此操作。甚至可以说您应该尝试通过一个充当其他服务器的服务器来完成所有访问。
  • @Chris 感谢您的想法。但是如果负责这个的进程没有运行呢?
  • 与其通信的机制如 startService() 将隐式启动它(如果尚未运行)。
  • @Chris 好的,我认为在这里使用广播接收器是合适的。

标签: android file-writing multiple-processes


【解决方案1】:

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

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

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

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

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2018-11-23
    • 2019-07-27
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多