In android,you can use FileLock to lock a file to prevent another process from writing to that file.
A file lock can be :
Exclusive or
shared
Shared : Multiple processes can hold shared locks on the same region of a single file.
Exclusive : Only a single process can hold an exclusive lock. No other process can simultaneously hold a shared lock overlapping the exclusive.
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.
Following example will clear your doubt how to lock a file and release it after performing operations on it.
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();
}