Java NIO通道FileLock
FileLock
鎖定或嘗試鎖定文件的給定部分。它屬於java.nio.channels
包,該功能在JDK 1.4以上版本可用。
FileLock
用於在共享模式或非共享模式下鎖定文件。它有兩個重要的方法如下:
-
FileLock.lock(long position, long size, boolean shared)
-
FileLock.tryLock(long position, long size, boolean shared)
上述方法使用參數作爲初始位置,文件大小鎖定和一個參數來決定是否共享鎖定。
創建文件鎖
當使用FileChannel
或AsynchronousFileChannel
的lock()
或tryLock()
方法之一獲取文件鎖時,將創建文件鎖定對象。
基本FileLock示例
下面來看看使用專用鎖定的通道在文件中寫入(附加)的程序(FileLockExample.java):
package com.yiibai;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class FileLockExample {
public static void main (String [] args)
throws IOException {
String input = "* end of the file.";
System.out.println("Input string to the test file is: " + input);
ByteBuffer buf = ByteBuffer.wrap(input.getBytes());
String fp = "testout-file.txt";
Path pt = Paths.get(fp);
FileChannel fc = FileChannel.open(pt, StandardOpenOption.WRITE,
StandardOpenOption.APPEND);
System.out.println("File channel is open for write and Acquiring lock...");
fc.position(fc.size() - 1); // position of a cursor at the end of file
FileLock lock = fc.lock();
System.out.println("The Lock is shared: " + lock.isShared());
fc.write(buf);
fc.close(); // Releases the Lock
System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");
PrintFile.print(fp);
}
}
PrintFile.java文件的內容如下 -
package com.yiibai;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class PrintFile {
public static void print(String path) throws IOException {
FileReader filereader = new FileReader(path);
BufferedReader bufferedreader = new BufferedReader(filereader);
String tr = bufferedreader.readLine();
System.out.println("The Content of testout-file.txt file is: ");
while (tr != null) {
System.out.println(" " + tr);
tr = bufferedreader.readLine();
}
filereader.close();
bufferedreader.close();
}
}
注意:在運行代碼之前,需要創建一個名稱爲「testout-file.txt」
的文本文件,文本文件的內容如下:
Welcome to yiibai.com
This is the example of FileLock in Java NIO channel.
執行上面示例代碼,得到以下結果 -
Input string to the test file is: * end of the file.
File channel is open for write and Acquiring lock...
The Lock is shared: false
Content Writing is complete. Therefore close the channel and release the lock.
The Content of testout-file.txt file is:
Welcome to yiibai.com
This is the example of FileLock in Java NIO channel.* end of the file.