`
lengyingxin
  • 浏览: 57344 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一个简单的FileLock实例

阅读更多
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockDemo {

	/**
	 * Filelock 防止程序在运行期间,线程在访问文件的过程中修改文件导致Buffer中
	 * 的部分或者全部内容不可读,造成程序异常。
	 * 例子中展示的是新开以个线程访问主线程Filelock的文件。
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		File file = new File("D://in.txt");
		FileOutputStream fis = new FileOutputStream(file);
		FileChannel fc = fis.getChannel();
		FileLock flock = fc.tryLock();
		if(flock.isValid()){
			System.out.println(file.getName()+ "is locked");
		}
		new Thread(){
			public void run(){
				try{
					File file = new File("D://in.txt");
					FileOutputStream fi = new FileOutputStream(file);
					fi.write('b');
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}.run();
		flock.release();
		System.out.println(file.getName()+ "is released");
		fc.close();
		fis.close();
	}

}

结果是该文件无法被新起的线程访问,运行结果:
in.txtis locked
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
at java.io.FileOutputStream.write(Native Method)
at com.cn.tibco.nio.FileLockDemo$1.run(FileLockDemo.java:32)
at com.cn.tibco.nio.FileLockDemo.main(FileLockDemo.java:37)
in.txtis released
0
1
分享到:
评论
1 楼 Shen.Yiyang 2012-09-05  
文件锁没有wait to lock的功能,所以说他能制造无法访问的异常,但是后续的处理非常麻烦

相关推荐

Global site tag (gtag.js) - Google Analytics