java文件鎖定一般都通過FileChannel來實現。主要涉及如下2個方法:
- tryLock() throws IOException 試圖獲取對此通道的文件的獨占鎖定。
- tryLock(long position, long size, boolean shared) throws IOException 試圖獲取對此通道的文件給定區域的鎖定。
1 import java.io.*; 2 import java.nio.channels.*; 3 4 public class LockFileDemo { 5 6 public static void main(String[] args) throws Exception { 7 String filePath = "c:\\test.txt"; 8 9 File file = new File(filePath); 10 RandomAccessFile raf = new RandomAccessFile(file, "rw"); 11 FileChannel fc = raf.getChannel(); 12 FileLock fl = fc.tryLock(); 13 14 if (fl.isValid()) { 15 System.out.println("Get the lock successed!"); 16 17 // 測試讀線程 18 ReadFile rf = new ReadFile(file); 19 rf.start(); 20 21 // 測試寫線程 22 // WriteFile wf = new WriteFile(file,"This is a test!----幻影"); 23 // wf.start(); 24 25 } 26 27 fl.release(); 28 System.out.println("release the lock!"); 29 raf.close(); 30 } 31 } 32 33 /**** 34 * 寫文件 35 * 36 * @author Administrator 37 * 38 */ 39 class WriteFile extends Thread { 40 File file; 41 String context; 42 43 public WriteFile() { 44 45 } 46 47 public WriteFile(File file, String context) { 48 this.file = file; 49 this.context = context; 50 } 51 52 public void run() { 53 FileWriter fw = null; 54 55 try { 56 fw = new FileWriter(file); 57 fw.write(context); 58 fw.flush(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 } 64 65 /**** 66 * 讀文件 67 * 68 * @author Administrator 69 * 70 */ 71 class ReadFile extends Thread { 72 File file; 73 74 public ReadFile() { 75 } 76 77 public ReadFile(File file) { 78 this.file = file; 79 } 80 81 public void run() { 82 FileReader fr = null; 83 try { 84 fr = new FileReader(file); 85 86 int c; 87 System.out.println("----------開始文件讀取----------"); 88 while ((c = fr.read()) != -1) { 89 System.out.print((char) c); 90 } 91 System.out.println(""); 92 System.out.println("----------文件讀取完畢----------"); 93 } catch (FileNotFoundException e) { 94 System.out.println("文件不存在!"); 95 } catch (IOException e) { 96 e.printStackTrace(); 97 } finally { 98 if (fr != null) { 99 try { 100 fr.close(); 101 } catch (IOException e) { 102 e.printStackTrace(); 103 } 104 } 105 } 106 } 107 }
程序輸出:
Get the lock successed! release the lock! ----------開始文件讀取---------- This is a test!----幻影 ----------文件讀取完畢----------
tryLock等同於tryLock(0L, Long.MAX_VALUE, false) ,它獲取的是獨占鎖,所以一定是在釋放鎖之后,才能讀取到文件內容。
也就是說,上例中,一定會先打印“release the lock!”,然后再打印出文件內容。
將上面的代碼改成(共享鎖):
FileLock fl = fc.tryLock(0, file.length(), true);//共享鎖 ....... Thread.sleep(2000);//為了區分清楚點 fl.release(); System.out.println("release the lock!"); raf.close();
那么才可能先打印出文件內容,然后打印“release the lock!”