这是一个代码片段,我正在打开一个文件,用于同时写入两个FileOutputStream
。如何判断文件是否在Android中进行读写?
FileOutputStream fis = null;
File openFile = new File("myfile");
try {
fis = new FileOutputStream(openFile);
Toast toast = Toast.makeText(getApplicationContext(), "Opened", Toast.LENGTH_SHORT);
toast.show();
}
catch (FileNotFoundException e1) {
Toast toast = Toast.makeText(getApplicationContext(), "FileNotFound", Toast.LENGTH_SHORT);
toast.show();
}
// now try to open it again
FileOutputStream fis2 = null;
try {
fis2 = new FileOutputStream(openFile);
Toast toast = Toast.makeText(getApplicationContext(), "Opened2", Toast.LENGTH_SHORT);
toast.show();
}
catch (Exception e1) {
Toast toast = Toast.makeText(getApplicationContext(), "Exception: " + e1.getMessage(), Toast.LENGTH_SHORT);
toast.show();
}
我最终得到了两个Toast
消息“Opened”和“Opened2”。
我需要确保我没有打开一个文件来读取/写入/删除当前打开的另一个实例写入。如何确保我不修改当前可以写入的文件?
+1有关lsof实用程序的信息 - 它对我的情况有所帮助 – ol0
没有办法说“我即将阅读该文件,请确保其他进程在完成之前无法写入”?我正在使用SharedPreferences,并在一段时间后丢失,但在使用Android API时,我无法使用FileLock。 – 3c71