刚学了nio,不是特别了解,nio只有FileChannel可用?
解决方案 »
- 线程问题
- 一个关于java.lang.ClassCastException: java.lang.Class的问题
- 如何用Eclipse+jboss写个ejb的客户端测试程序,测试ejb的有效性呢?
- 关于快速排序
- 请问 如何才能操作网页的document
- <thinking in java>学习笔记跟大家一起分享,有什么不对的请指出.
- 谁能谈一谈接口的作用?
- java同步 是什么意思?
- Exception in thread "main"java.lang.NoClassDefFoundError:HelloDate(在线)
- 如何去系统的当前时间?
- 怎么获得从其他数据库同步过来的新的数据?
- 如何查找两个字符串中是否有相同的子串
DatagramChannel 针对面向数据报套接字的可选择通道。
ServerSocketChannel 针对面向流的侦听套接字的可选择通道。
SocketChannel 针对面向流的连接套接字的可选择通道。
等可用。而且nio除了通道外,还提供了缓冲区与字符集的API。均可独立于通道使用。最后,回答标题中的问题:
nio中,没有直接提供对System.in(类型为InputStream)和System.out(类型为PrintStream)的包装类。
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比较慢?还是我写错了?
System.in与System.out两个属性,他们的属性是public static final属性,但是System类里面有一个setIn与一个setOut方法。
晕哦……用了好几次nio,居然一直没发现Channels类……学习了!