Java-nio-file-channel

提供:Dev Guides
移動先:案内検索

Java NIO-ファイルチャネル

説明

すでに述べたように、Java NIOチャネルのFileChannel実装は、作成、変更、サイズなどを含むファイルのメタデータプロパティにアクセスするために導入されています。このファイルチャネルに加えて、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 finddevguides".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 finddevguides