Javaでチャネル「Java.nio.channels.Pipe」を利用する方法

サンプルコード
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeStartnews24 {
public static void main(String[] args) {
//初期化
Pipe pipe = null;
try {
pipe = Pipe.open();
} catch (IOException e) {
e.printStackTrace();
}
Pipe.SinkChannel skChannel = pipe.sink();
String testData = “start to check java NIO Channels Pipe";

ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.clear();
buffer.put(testData.getBytes());

buffer.flip();
//データを書き込み
while(buffer.hasRemaining()) {
try {
skChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
//データを読み込む
Pipe.SourceChannel sourceChannel = pipe.source();
buffer = ByteBuffer.allocate(512);
//コンソールにデータを出力
try {
while(sourceChannel.read(buffer) > 0){

buffer.flip();

while(buffer.hasRemaining()){
char ch = (char) buffer.get();
System.out.print(ch);
}
buffer.clear();
}
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}

Java

Posted by arkgame