Hi,
I'm trying to lock a file with Java in Windows environment with FileLock and I got an issue : after I lock the file it can still be accessed by other processes at least on some level.
Example code follows:
public class SimpleLockExample {
public static void main(String[] args) throws Exception {
String filename = "loremlipsum.txt";
File file = new File(filename);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
FileLock lock = null;
try {
lock = channel.tryLock();
String firstLine = raf.readLine();
System.out.println("First line of file : " + firstLine);
waitForEnter();
lock.release();
} catch (OverlappingFileLockException e) {
e.printStackTrace();
}
lock.release();
System.out.println("Lock released");
channel.close();
}
private static void waitForEnter() throws Exception {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
reader.readLine();
reader.close();
}
}
Now, when I lock my file with this example, it is locked :
- It can't be deleted by Windows
- Eclipse refuses to open it
... but it isn't still totally bulletproof:
- If I open it with Scite (a text editor), for example, no content is shown but if I select to save the file (empty as opened or with some content written), it succeeds and the contents of the file is cleared... (no content exists there afterwards even if I had written something with Scite)
Is there some way to prevent the file totally from being overwritten/cleared by other processes with Java in Windows?
If I've understood right, I'm using exclusive lock atm. With shared lock there are even more things that can be done.
This test was run with Windows 2000.
br, Touko