Java nio(一)


jdk1.4 javaが提供されます.Nioパッケージは、I/Oのパフォーマンスを根本的に改善することが可能ですが、nioは以前のI/Oよりも複雑で、より下位の操作とより細かいapiを提供しています.勉強するのはそんなに早く上手になるわけではない,専門の本がある.
nioを紹介します.nioフレームワーク全体の各クラス間の関係をよりよく整理することで、nioパッケージを柔軟に使用できることを望んでいます.
Nioは通常、3つのオブジェクトに関連する必要があります.
1、データソース:ファイルから取得したFileInputStream/FileOutputStream、socketから取得した入出力ストリームなど
2、バッファオブジェクト(buffer):nioは一連のbufferオブジェクトを定義し、最も基本的なのはByteBufferであり、その他にもbooleanタイプのほか、対応するbufferタイプの様々な基本データ型がある.これらのbufferを用いる一般的なプロセスは、データソースからByteBufferに読み出され、その後、ByteBufferが用いる.asXxxBuffer()は、特定の基本タイプに変換され、この基本タイプのbufferを操作する.基本タイプをByteBufferタイプに変換し、データソースに書き込みます.
3、チャネルオブジェクト(channel):彼はデータソースへの接続を提供し、ファイルからFileChannelを取得し、SocketからSocketChannelを取得し、仲介者である.データ・ソースとバッファ間の読み書き操作が提供されます.
私たちは彼ら3人の関係を説明するために同じ言葉を使うことができます.
channelオブジェクトは、データソースとバッファ間の読み書き操作を提供し、データソースとバッファの橋渡しであり、この橋渡しを通じてデータが両者の間を流れる.
まず、この仲介チャネルクラスの構造全体を見てみましょう.

Channel < Closable
WritableByteChannel < Channel
InterruptibleChannel < Channel
ReadableByteChannel < Channel
GetherByteChannel < WritableByteChannel 
ByteChannel < WritableByteChannel,ReadableByteChannel 
ScatteringByteChannel < ReadableByteChannel 

Channelインタフェースでは、次の2つのメソッドが宣言されています.
close()チャネルを閉じる
チャネルが開いているかどうかをテストするためのisOpen()
その他のチャネル:
ByteChannelは単純にWritableByteChannelとReadableChannelを統合しただけで、ScatteringByteChannelインタフェースはReadableChannelインタフェースを拡張し、読み取りとデータの追加
異なるバッファに分散する方法で、GatheringByteChannelインタフェースは、WritableByteChannelに基づいて複数の独立したバッファをドライブに書き込む方法を追加します.

Closeable:
void close()//       ,     
Channel:
void close()//    
void boolean isOpen()//        
ReadableByteChannel:
int read(ByteBuffer input)
//        input    ,        ,      ,  -1
WritableByteChannel:
int write(ByteBuffer output)
//      output       ,       
ByteChannel      ReadableByteChannel WritableByteChannel   
ScatteringByteChannel:
int read(ByteBuffer[] inputs)
//        inputs      ,       ,      ,  -1
int read(ByteBuffer[] inputs,int offset,int length)
//       inputs[offset]---inputs[offeset+length-1]    
GatherByteChannel:
int write(ByteBuffer[] outputs);
// outputs          
int write(ByteBuffer[] outputs,int offset,int length);
  outputs[offset]-->outputs[offset+length-1]        

例:(各種Exceptionは無視)

File file = new File("C:\\test.txt");
FileOutputStream fos = new FileOutputStream(file);
FileChannel outputChannel = fos.getChannel();
String str = "Hello,just a test";
ByteBuffer bb = ByteBuffer.wrap(str.getBytes());
outputChannel.write(bb);

ここまでまとめておき、次回は様々なBufferとその操作をまとめます.