在多线程的程序中,如果有一个共享文件要被访问或者编辑,如何实现文件的独占模式下的读写呢?
用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!
这一行处理!