1. 程式人生 > >NIO的pipe管道

NIO的pipe管道

管道(Pipe)

Java的NIO管道是2個執行緒之間的單向資料連線,Pipe有一個source通道和一個sink通道,資料會被寫到sink通道,從source通道讀取

package com.nio;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class TestPipe {
    @Test
    public void test1() throws IOException{
//1. 獲取管道 Pipe pipe = Pipe.open(); //2. 將緩衝區中的資料寫入到管道 ByteBuffer buf = ByteBuffer.allocate(1024); Pipe.SinkChannel sinkChannel = pipe.sink(); buf.put("通過單向管道傳送資料".getBytes()); buf.flip(); sinkChannel.write(buf); //3. 讀取緩衝區中的資料 Pipe.
SourceChannel sourceChannel = pipe.source(); buf.flip(); int len = sourceChannel.read(buf); System.out.println(new String(buf.array(),0,len)); sourceChannel.close(); sinkChannel.close(); } }