码迷,mamicode.com
首页 > 编程语言 > 详细

java的NIO管道用法

时间:2014-09-25 17:39:57      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   java   ar   数据   2014   on   c   

Java的NIO中的管道,就类似于实际中的管道,有两端,一段作为输入,一段作为输出。也就是说,在创建了一个管道后,既可以对管道进行写,也可以对管道进行读,不过这两种操作要分别在两端进行。有点类似于队列的方式。

我们在测试例子中给出一个非常简单的管道操作,先向管道写入内容,再从管道读出内容。

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());
		}
	}

}

输出结果

bubuko.com,布布扣


我们可以看到,已经可以完成我们需要的目标了。注意,我在这个地方编程的时候,出现了一点错误,就是我在读取管道的时候,没有设置getBuf.flip(),导致无法读出数据,这个函数非常重要,在完成buffer读取内容之后,一定要设置一下读标志,恢复指针到原始位置,才能读取到全部内容。

java的NIO管道用法

标签:blog   http   io   java   ar   数据   2014   on   c   

原文地址:http://blog.csdn.net/itbuluoge/article/details/39552769

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!