开发者

How do tell if a file is opened for reading/writing in Android?

开发者 https://www.devze.com 2023-03-29 00:34 出处:网络
Here is a code snippet where I am opening a file for writing with two FileOutputStreams at the same time.

Here is a code snippet where I am opening a file for writing with two FileOutputStreams at the same time.

FileOutputStream fis = null;
File openFile = new File("myfile");
try {
    fis = new FileOutputStream(openFile);
    Toast toast = Toast.makeText(getApplicationContext(), "Opened", Toast.LENGTH_SHORT);
    toast.s开发者_JS百科how();
}
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();
}

I end up getting two Toast messages, "Opened" and "Opened2".

I need to make sure I don't open a file for reading/writing/deleting that is currently open for writing by another instance. How to I ensure I do not modify a file that is currently open for writing?


I need to make sure I don't open a file for reading/writing/deleting that is currently open for writing by another instance.

What do you mean by another instance?

  • If this is another thread in your application use the synchronization for read/write methods.
  • If this is another process created by yourself (application, service etc.) use exclusive FileLock to coordinate file read/write operations between processes.
  • If this is another process you don't control (i.e. created by someone else) you can check whether file is currently opened by inspecting /proc/…/fd/ tree, as lsof utility does. However this usually requires you to have root privileges.

Hope that give you a clue. Let me know if you need further assistance.


FileObserver might help you.


You could just perform a null check

if (null == fis)
// then create output stream

If fis was opened earlier, it wouldn't be null, and you wouldn't end up opening another output stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消