Channel詳解

 複製自:http://www.cnblogs.com/youngKen/p/4921092.htmlhtml

 java.nio.channels.FileChannel封裝了一個文件通道和一個FileChannel對象,這個FileChannel對象提供了讀寫文件的鏈接。java

一、接口

二、通道操做

  a、全部通道接口都是擴展自java.nio.channels.Channel,該通道接口的聲明有兩個方法:

  • 關閉通道close()方法;
  • 測試通道狀態isOpen(),打開true,關閉false。
//源碼
public interface Channel extends Closeable { boolean isOpen(); void close() throws IOException; }

  由於通道接口都是擴展AutoCloseable接口,如是是在帶資源的try代碼中建立他們,那麼全部通道將會自動關閉。測試

  b、ReadableByteChannel接口:

  • int read(ByteBuffer in) 將字節流從設備(通道)讀取緩衝區。到達結尾返回-1;
//源碼
public interface ReadableByteChannel extends Channel {
int read(ByteBuffer var1) throws IOException;
}

  c、WriteableByteChannel接口:code

  • int write(ByteBuffer out) 將字節流從緩衝區寫入到設備(通道)中。
//源碼
public interface WritableByteChannel extends Channel { int write(ByteBuffer var1) throws IOException; }

  d、ByteChannel接口:htm

  • 這接口沒有新的方法,繼承自ReadableByteChannel和WritableByteChannel。
public interface ByteChannel extends ReadableByteChannel, WritableByteChannel {
}

  e、ScatteringByteChannel接口:對象

  • int read(ByteBuffer[] in) 將字節從通道讀入到緩衝區中,若是到達尾部返回-1;
  • int read(ByteBuffer[] in, int offset, int length) 將字節從offset開始到length讀入到緩衝區中。
public interface ScatteringByteChannel extends ReadableByteChannel {
    long read(ByteBuffer[] var1) throws IOException;

    long read(ByteBuffer[] var1, int var2, int var3) throws IOException;
}

  f、GatheringByteChannel接口:blog

  • int write(ByteBuffer[] out) 將字節從緩衝區寫入到通道中,返回字節數;
  • int write(ByteBuffer[] out, int offset, int length) 將字節從offset開始到length讀入到通道中。
public interface GatheringByteChannel extends WritableByteChannel {
    long write(ByteBuffer[] var1) throws IOException;

    long write(ByteBuffer[] var1, int var2, int var3) throws IOException;
}
相關文章
相關標籤/搜索