Java Nio 简明教程

Java NIO - File Channel

Description

如前所述,Java NIO 通道的 FileChannel 实现被引入以访问文件的元数据属性,包括创建、修改、大小等。除此之外,文件通道是多线程的,这再次使 Java NIO 比 Java IO 更有效。

As already mentioned FileChannel implementation of Java NIO channel is introduced to access meta data properties of the file including creation, modification, size etc.Along with this File Channels are multi threaded which again makes Java NIO more efficient than Java IO.

一般来说,我们可以说 FileChannel 是连接到文件的通道,通过它你可以从文件读取数据,并向文件写入数据。FileChannel 的另一个重要特征是它不能被设置为非阻塞模式,并且始终以阻塞模式运行。

In general we can say that FileChannel is a channel that is connected to a file by which you can read data from a file, and write data to a file.Other important characteristic of FileChannel is this that it cannot be set into non-blocking mode and always runs in blocking mode.

我们无法直接获取文件通道对象,文件通道对象可以通过以下方法获得:

We can’t get file channel object directly, Object of file channel is obtained either by −

  1. getChannel() − method on any either FileInputStream, FileOutputStream or RandomAccessFile.

  2. open() − method of File channel which by default open the channel.

文件通道的对象类型取决于调用对象创建时所调用的类类型,即如果对象是通过调用 FileInputStream 的 getchannel 方法创建的,则文件通道将被打开以进行读取,并且在尝试写入时将抛出 NonWritableChannelException。

The object type of File channel depends on type of class called from object creation i.e if object is created by calling getchannel method of FileInputStream then File channel is opened for reading and will throw NonWritableChannelException in case attempt to write to it.

Example

以下示例显示如何从 Java NIO FileChannel 读取和写入数据。

The following example shows the how to read and write data from Java NIO FileChannel.

以下示例从 C:/Test/temp.txt 的文本文件中读取数据,并将内容打印到控制台。

Following example reads from a text file from C:/Test/temp.txt and prints the content to the console.

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();
   }
}

Output

Hello World! Welcome to TutorialsPoint