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;
}
相关文章
相关标签/搜索