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.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();
}
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?
What do you mean by another instance?
FileLockto coordinate file read/write operations between processes./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.