Java NIO - 檔案通道



描述

如前所述,Java NIO 通道中的 FileChannel 實現被引入以訪問檔案的元資料屬性,包括建立、修改、大小等。除此之外,File 通道是多執行緒的,這又使得 Java NIO 比 Java IO 效率更高。

一般來說,我們可以說 FileChannel 是一個連線到檔案的通道,你可以透過它從檔案中讀取資料和向檔案中寫入資料。FileChannel 的另一個重要特點是它不能被設定為非阻塞模式,並且始終以阻塞模式執行。

我們不能直接獲取檔案通道物件,檔案通道物件可以透過以下方式獲取 −

  • getChannel() − 在任何一個 FileInputStream、FileOutputStream 或 RandomAccessFile 上的方法。

  • open() − File 通道的方法,它預設開啟通道。

File 通道的物件型別取決於從物件建立中呼叫的類型別,即如果物件是透過呼叫 FileInputStream 的 getchannel 方法建立的,則 File 通道將被開啟用於讀取,並且會丟擲 NonWritableChannelException 以嘗試寫入它。

示例

以下示例展示瞭如何從 Java NIO FileChannel 中讀取和寫入資料。

以下示例從位於 C:/Test/temp.txt 的文字檔案中讀取,並將其內容列印到控制檯。

temp.txt

Hello World!

FileChannelDemo.java

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;

public class FileChannelDemo {
   public static void main(String args[]) throws IOException {
      //append the content to existing file 
      writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes()));
      //read the file
      readFileChannel();
   }
   public static void readFileChannel() throws IOException {
      RandomAccessFile randomAccessFile = new RandomAccessFile("C:/Test/temp.txt",
      "rw");
      FileChannel fileChannel = randomAccessFile.getChannel();
      ByteBuffer byteBuffer = ByteBuffer.allocate(512);
      Charset charset = Charset.forName("US-ASCII");
      while (fileChannel.read(byteBuffer) > 0) {
         byteBuffer.rewind();
         System.out.print(charset.decode(byteBuffer));
         byteBuffer.flip();
      }
      fileChannel.close();
      randomAccessFile.close();
   }
   public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException {
      Set<StandardOpenOption> options = new HashSet<>();
      options.add(StandardOpenOption.CREATE);
      options.add(StandardOpenOption.APPEND);
      Path path = Paths.get("C:/Test/temp.txt");
      FileChannel fileChannel = FileChannel.open(path, options);
      fileChannel.write(byteBuffer);
      fileChannel.close();
   }
}

輸出

Hello World! Welcome to TutorialsPoint
廣告
© . All rights reserved.