Channel详解

 复制自:http://www.cnblogs.com/youngKen/p/4921092.html

 java.nio.channels.FileChannel封装了一个文件通道和一个FileChannel对象,这个FileChannel对象提供了读写文件的连接。

1、接口

2、通道操作

  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接口:

  • int write(ByteBuffer out) 将字节流从缓冲区写入到设备(通道)中。
//源码
public interface WritableByteChannel extends Channel { int write(ByteBuffer var1) throws IOException; }

  d、ByteChannel接口:

  • 这接口没有新的方法,继承自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接口:

  • 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;
}
原文地址:https://www.cnblogs.com/SimplifyIT/p/6591643.html