在多線程的程序中,如果有一個共享文件要被訪問或者編輯,如何實現文件的獨佔模式下的讀寫呢?
用java.nio.channels.FileLock是一個比較好的辦法,實現的思路是先new一個名字genFile.lck的文件,
在通過getChannel().tryLock()方法返回一個FileLock. 如果是沒有人訪問,就會返回一個不爲空的引用,
如果有人正在訪問,則返回null,
這樣就不會打開別人正在編寫的文件了,
代碼如下:
private static final String GEN_LCK_FILE = "genFile.lck";
private static FileLock genLock = null;
public static void main(String args[]) {
try {
// Acquire an exclusive lock, assure manager is stand alone
genLock = new FileOutputStream(GEN_LCK_FILE).getChannel().tryLock();
if (null != genLock) {
//open the file you want!
} else {
System.err.println("this file has been open but other person!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != genLock) {
try {
genLock.release();
// delete the lock file
new File(GEN_LCK_FILE).delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
提示這裏的genFile.lck只是提供加鎖的文件,用它來判斷文件是否被訪問,真正要訪問修改的文件在代碼中
//open the file you want!
這一行處理!