java编程笔记15文件锁定操作

有时候打开文件会有这样的提示:该文件已被另一个程序占用,打开失败。这是因为另一个程序正在编辑该文件,并且不希望编辑过程中其他程序来修改这个文件,由此锁定了该文件。

在java中,使用filelock类来实现锁定文件,下面的代码演示了这种方法。

package fileoperation;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.nio.channels.filelock;
public class lockfile {
public static void main(string[] args) throws ioexception {
fileoutputstream fous = null;
filelock filelock = null;
try{
fous = new fileoutputstream("c:\\file_lock.txt");
filelock = fous.getchannel().trylock();//锁对象的获取方法,
//本线程锁定一分钟,一分钟内其他任何程序不能对该文件进行写操作
thread.sleep(60*1000);
}catch(exception e){
e.printstacktrace();
}finally{
if(filelock != null)
filelock.release();
if(fous != null)
fous.close();
}
}
}