File的加鎖
有時(shí)候,我們需要以獨(dú)占的方式訪問某個(gè)文件,因此,需要在打開文件時(shí),對(duì)文件上鎖,以防其他人或進(jìn)程也訪問該文件。Java本身提供了倆種鎖文件的方式:方式一:用RandomAccessFile類操作文件
RandomAccessFile的open方法,提供了參數(shù),實(shí)現(xiàn)以獨(dú)占的方式打開文件:
new RandomAccessFile(file, "rws")
其中的“rws”參數(shù)中,rw代表讀寫方式,s代表同步方式,也就是鎖。這種方式打開的文件,就是獨(dú)占方式。
方式二:用文件通道(FileChannel)的鎖功能
如:
RandomAccessFile raf = new RandomAccessFile(new File("c:\\test.txt"), "rw");
FileChannel fc = raf.getChannel();
FileLock fl = fc.tryLock();
if (fl.isValid()) {
System.out.println("get the lock!");
但這倆種方式,都只能通過RandomAccessFile訪問文件,如果只能通過InputStream來訪問文件,如用DOM分析XML文件,怎么辦呢?
其實(shí),F(xiàn)ileInputStream對(duì)象,也提供了getChannel方法,只是缺省的getChannel方法,不能鎖住文件,所以,如果需要,就必須自己重寫一個(gè)getChannel方法,如:
public FileChannel getChannel(FileInputStream fileIn, FileDescriptor fd) {
FileChannel channel = null;
synchronized (fileIn) {
channel = FileChannelImpl.open(fd, true, true, fileIn);
return channel;
}
}
其實(shí),主要是打開文件的第三個(gè)參數(shù)控制了對(duì)文件的操作模式,如果設(shè)置為false,就不能鎖住文件,缺省的getChannel方法,就是false,因此,不能鎖住文件。
posted on 2006-05-23 08:54 扭轉(zhuǎn)乾坤 閱讀(458) 評(píng)論(0) 編輯 收藏 所屬分類: JAVA使用技巧