Java NIO中的FileChannel是一個連接到文件的通道。可以通過文件通道讀寫文件。FileChannel無法設置爲非阻塞模式,它總是運行在阻塞模式下。
- 打開FileChannel
在使用FileChannel之前,必須先打開它。但是,我們無法直接打開一個FileChannel,需要通過使用一個InputStream、OutputStream或RandomAccessFile來獲取一個FileChannel實例(這裏通過InputStream和OutputStream講解,前面已經使用了RandomAccessFile)
@Test
@SuppressWarnings("resource")
public void fileChannel() {
try {
// 通過文件輸入流獲取文件通道對象
FileChannel inChannel = new FileInputStream(
new File("D:/360Downloads/task.ini")).getChannel();
// 通過文件輸出流獲取追加文件通道對象
FileChannel outChannel = new FileOutputStream(
new File("D:/360Downloads/task.ini"), true).getChannel();
// 獲取緩衝區
ByteBuffer buf = ByteBuffer.allocate(128);
buf.clear();
// 讀取數據
int len = inChannel.read(buf);
System.out.println(new String(buf.array(), 0, len));
// 追寫寫數據
ByteBuffer buf2 = ByteBuffer
.wrap("Hello jack! Nice to meet to you ! \n".getBytes());
outChannel.write(buf2);
// 調用position(long pos)方法設置FileChannel當前開始讀寫的位置。
System.out.println("------------------------------------");
buf.clear();
inChannel.position(30);
int hasRead = inChannel.read(buf);
while (-1 != hasRead) {
buf.flip();
// 是否已經達到限制:當前讀的位置是否已經 > inChannel.size()
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
buf.clear();
hasRead = inChannel.read(buf);
}
// 釋放資源
inChannel.close();
outChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
FileChannel的truncate方法
可以使用FileChannel.truncate()方法截取一個文件。截取文件時,文件將中指定長度後面的部分將被刪除。如:
channel.truncate(1024);
FileChannel的force方法
FileChannel.force(true);方法將通道里尚未寫入磁盤的數據強制寫到磁盤上。