现在的位置: 首页 > 综合 > 正文

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

2013年07月02日 ⁄ 综合 ⁄ 共 622字 ⁄ 字号 评论关闭

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

  在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();
			}		
	}
	
}

抱歉!评论已关闭.