软件编程
位置:首页>> 软件编程>> java编程>> java的NIO管道用法代码分享

java的NIO管道用法代码分享

作者:IT老蒋  发布时间:2022-05-01 23:52:53 

标签:java,nio,管道

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

这里是Pipe原理的图示:

java的NIO管道用法代码分享

创建管道

通过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);
}

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

 


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

输出结果

java的NIO管道用法代码分享

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

来源:http://blog.csdn.net/itbuluoge/article/details/39552769

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com