android - 在Android中,如何防止多个进程写入同一个文件

标签 android file-writing multiple-processes

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

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

最佳答案

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

关于android - 在Android中,如何防止多个进程写入同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689806/

相关文章:

debugging - 防止调试 session 在每次低级退出后暂停

c++ - 等待多个对象,仅给出已创建的进程 vector

java - Android:ListView ..在单击模式和多选模式之间转换(如:消息应用程序)

python - 如何将日志消息写入文件

android - Jquery 移动对话框不随动态内容滚动

python - 如何将数据保存到下一列

Golang : file. Seek 和 file.WriteAt 未按预期工作

c - C 的管道问题。是否有额外的进程正在执行?

java - TimePicker 未定义 setText(String) 方法

android - 如何在生命周期独立类中处理 Observables?