java的nio中的管道,就类似于实际中的管道,有两端,一段作为输入,一段作为输出。也就是说,在创建了一个管道后,既可以对管道进行写,也可以对管道进行读,不过这两种操作要分别在两端进行。有点类似于队列的方式。
这里是pipe原理的图示:
创建管道
通过pipe.open()方法打开管道。例如:
pipe pipe = pipe.open();
向管道写数据
要向管道写数据,需要访问sink通道。像这样:
pipe.sinkchannel sinkchannel = pipe.sink();
通过调用sinkchannel的write()方法,将数据写入sinkchannel,像这样:
?
|
1
2
3
4
5
6
7
8
|
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);
}
|
我们在测试例子中给出一个非常简单的管道操作,先向管道写入内容,再从管道读出内容。
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package com.test.nio;
import java.io.ioexception;
import java.nio.bytebuffer;
import java.nio.channels.pipe;
public class testpipea {
/**
* @param args
* @throws exception
*/
public static void main(string[] args) throws exception {
//创建一个管道
pipe pipe=pipe.open();
//创建一个写管道
pipe.sinkchannel sinkchannel=pipe.sink();
string newdata="itbuluoge.com says:"+system.currenttimemillis();
bytebuffer buf=bytebuffer.allocate(48);
buf.clear();
buf.put(newdata.getbytes());
buf.flip();
/*向管道写入内容*/
while(buf.hasremaining())
{
sinkchannel.write(buf);
}
/*创建一个读管道*/
pipe.sourcechannel sourcechannel=pipe.source();
bytebuffer getbuf=bytebuffer.allocate(48);
int bytesread=sourcechannel.read(getbuf);
getbuf.flip();
/*从管道读出内容*/
while(getbuf.hasremaining())
{
system.out.print((char)getbuf.get());
}
}
}
|
输出结果
我们可以看到,已经可以完成我们需要的目标了。注意,我在这个地方编程的时候,出现了一点错误,就是我在读取管道的时候,没有设置getbuf.flip(),导致无法读出数据,这个函数非常重要,在完成buffer读取内容之后,一定要设置一下读标志,恢复指针到原始位置,才能读取到全部内容。
以上就是本文关于java的nio管道用法代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/itbuluoge/article/details/39552769
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 83
-
2025-05-29 62
-
2025-05-25 37
-
2025-05-29 12
-
2025-05-27 40
热门评论



