刚学了nio,不是特别了解,nio只有FileChannel可用?

解决方案 »

  1.   

    非也。就只说通道,除了FileChannel外,还有
    DatagramChannel 针对面向数据报套接字的可选择通道。
    ServerSocketChannel 针对面向流的侦听套接字的可选择通道。 
    SocketChannel 针对面向流的连接套接字的可选择通道。
    等可用。而且nio除了通道外,还提供了缓冲区与字符集的API。均可独立于通道使用。最后,回答标题中的问题:
    nio中,没有直接提供对System.in(类型为InputStream)和System.out(类型为PrintStream)的包装类。
      

  2.   

    恩,好像是可以封装的。System.in:
    ReadableByteChannel ch = Channels.newChannel(System.in);
    ByteBuffer buf = ByteBuffer.allocate(1024 * 8);while (ch.read(buf) != -1) {
    buf.flip();
    System.out.print(new String(buf.array()));
    }System.out:
    WritableByteChannel fc = Channels.newChannel(System.out);
    ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
    for (int i = 1; i <= 1000000; ++i) {
    String t = Integer.toString(i) + "\r\n";
    buf.put(t.getBytes());

    if (i % 100 == 0) {
    buf.flip();
    fc.write(buf);
    buf.clear();
    }
    }但是还有一个问题,System.in是比较快的,比BufferedReader要快,但是System.out的处理好像非常慢,要0.6s多,而PrintWriter只要0.4s,难道nio比较慢?还是我写错了?
      

  3.   

    这里有一个很有意思的现象
    System.in与System.out两个属性,他们的属性是public static final属性,但是System类里面有一个setIn与一个setOut方法。
      

  4.   

    厄然后呢?我write之前已经重定向到一个文件中了。这个也影响速度么?
      

  5.   

    [顶2楼]
    晕哦……用了好几次nio,居然一直没发现Channels类……学习了!