Java NIO Pipe
2016-01-19 19:51
501 查看
Java NIO 管道是2个线程之间的单向数据连接。
这里是Pipe原理的图示:
通过调用SinkChannel的
调用source通道的
Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
这里是Pipe原理的图示:
创建管道
通过Pipe.open()方法打开管道。例如:
Pipe pipe = Pipe.open();
向管道写数据
要向管道写数据,需要访问sink通道。像这样:Pipe.SinkChannel sinkChannel = pipe.sink();
通过调用SinkChannel的
write()方法,将数据写入
SinkChannel,像这样:
String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { sinkChannel.write(buf); }
从管道读取数据
从读取管道的数据,需要访问source通道,像这样:Pipe.SourceChannel sourceChannel = pipe.source();
调用source通道的
read()方法来读取数据,像这样:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = sourceChannel.read(buf);
read()方法返回的int值会告诉我们多少字节被读进了缓冲区。
相关文章推荐
- Java NIO Java NIO DatagramChannel
- Java NIO ServerSocketChannel
- Java NIO SocketChannel
- 谈Spring的理解
- Java NIO FileChannel
- Java NIO Selector
- java文件复制函数
- 【转】Java中如何遍历Map对
- eclipse 中文乱码
- eclipse汉字太小解决办法
- eclipse中文乱码
- Java NIO 通道之间的数据传输
- Java NIO Scatter/Gather
- POJ 1088 Java:滑雪(动态规划)
- 利用Spring AOP监控方法(二)日志存放位置
- RabbitMQ入门教程 For Java【7】 - Window下的安装与配置
- POJ 1001 Java:求高精度幂
- 出现java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher错误
- Java多线程(3) Volatile的实现原理
- Spring声明式事务配置管理方法