在Android中,如何防止多个进程写入同一个文件
在我的应用程序中,我将检查之前是否生成了唯一id,如果没有,它将生成一个并将其写入文件。但在多进程应用程序中,如果多个进程都发现以前没有生成uid,则当它们尝试写入同一个文件时,会出现问题在Android中,如何防止多个进程写入同一个文件,android,file-writing,multiple-processes,Android,File Writing,Multiple Processes,在我的应用程序中,我将检查之前是否生成了唯一id,如果没有,它将生成一个并将其写入文件。但在多进程应用程序中,如果多个进程都发现以前没有生成uid,则当它们尝试写入同一个文件时,会出现问题 那么在android中,如何防止多个进程写入同一个文件?在android中,您可以使用FileLock锁定一个文件,以防止另一个进程写入该文件 文件锁可以是: 排他或 共享 共享:多个进程可以在单个文件的同一区域上持有共享锁 独占:只有一个进程可以持有独占锁。没有其他进程可以同时持有与独占进程重叠的共享锁 f
那么在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的许多IPC机制中的一个来请求该进程这样做。甚至有人会说,你应该尝试通过一个将作为其他服务器的服务器来完成所有访问。@Chris谢谢你的想法。但如果负责此操作的进程没有运行该怎么办?与之通信的机制,如startService()将在尚未运行时隐式启动它。@Chris ok,我认为在这里使用广播接收器是合适的。