雖然用線程的synchronized方法也可以達到封鎖的效果,但很多情況都會增強了程序的複雜性;現在介紹一種簡單的類----java.nio.channels.FileLock和java.nio.channels.FileChannel;
java.io.FileInputStream,java.io.RandomAccessFile等類中都有一個可以得到FileChannel類(用於讀取、寫入、映射和操作文件的通道。)的方法叫getChannel()(即public final FileChannel getChannel()),而FileChannel類下又有一個可以得到FileLock類(表示文件區域鎖定的標記)的方法叫tryLock()(即public final FileLock tryLock() throws IOException);現在把它們串起來,你大概想到怎樣用文件鎖了吧。。下面來看看我寫的一個小程序,重點說明文件鎖的用法。
package ccp330.gucheng.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockTest {
public static void main(String[] args) {
File fdir=new File("D:/gucheng.txt");
try {
RandomAccessFile ranStream=new RandomAccessFile(fdir, "rw");
FileChannel channel=ranStream.getChannel();
FileLock lock=channel.tryLock();
String str=null;
while( ( str=( ranStream.readLine() ) ) != null){
str= new String(str.getBytes("ISO-8859-1"),"gb2312"); //此行用於處理雙字節字符(例如:中文),單字節的字符可以不寫。
System.out.println(str);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.release();
ranStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
File fdir=new File("D:/gucheng.txt");
try {
RandomAccessFile ranStream=new RandomAccessFile(fdir, "rw");
FileChannel channel=ranStream.getChannel();
FileLock lock=channel.tryLock();
String str=null;
while( ( str=( ranStream.readLine() ) ) != null){
str= new String(str.getBytes("ISO-8859-1"),"gb2312"); //此行用於處理雙字節字符(例如:中文),單字節的字符可以不寫。
System.out.println(str);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.release();
ranStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}