nio

jdk1.4中引入lava.nio.*,使用通道和缓冲器提高速度:体现在文件IO和网络IO

通道(Channel):即数据

缓冲器:承载一定大小的数据

唯一与通道交互的缓冲器是ByteBuffer

文件IO中的应用:

public class ChannelCopy {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    if(args.length != 2) {
      System.out.println("arguments: sourcefile destfile");
      System.exit(1);
    }
    FileChannel
      in = new FileInputStream(args[0]).getChannel(),
      out = new FileOutputStream(args[1]).getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
    while(in.read(buffer) != -1) {
      buffer.flip(); // Prepare for writing
      out.write(buffer);
      buffer.clear();  // Prepare for reading
    }
  }
} 

还可以将通道直接相连:

public class TransferTo {
  public static void main(String[] args) throws Exception {
    if(args.length != 2) {
      System.out.println("arguments: sourcefile destfile");
      System.exit(1);
    }
    FileChannel
      in = new FileInputStream(args[0]).getChannel(),
      out = new FileOutputStream(args[1]).getChannel();
    in.transferTo(0, in.size(), out);
    // Or:
    // out.transferFrom(in, 0, in.size());
  }
}

网络IO中的应用:

http://blog.csdn.net/anxpp/article/details/51512200

https://my.oschina.net/hosee/blog/615269

java7中新的异步通道:

AsynchronousFileChannel--文件io

AsynchronousSocketChannel--套接字io

AsynchronousServerSocketChannel--用于套接字接受异步连接

将来式与回调式

NetworkChannel

MulticastChannel

 

posted on 2017-03-08 11:18  伪善者ql  阅读(146)  评论(0编辑  收藏  举报

导航