Java管道流PipedStream

来源:互联网 发布:js 24小时时间插件 编辑:程序博客网 时间:2024/05/01 05:10

package com.wj.pipedstream;


import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
 *
 * @author wJing
 * 管道流
 */
public class PipedStreamDemo {

    public static void main(String[] args) throws Exception {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        in.connect(out);
        read r = new read(in);
        Write w = new Write(out);
        
        new Thread(r).start();
        new Thread(w).start();
    }

}

class read implements Runnable {
    PipedInputStream pis = null;
    public read(PipedInputStream pis) {
        this.pis = pis;
    }
    @Override
    public void run() {
        try {
            byte [] buf = new byte[1024];
            int len = pis.read(buf);
            String s = new String(buf,0,len);
            System.out.println(s);
            pis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
class Write implements Runnable {
    PipedOutputStream pos = null;
    public Write(PipedOutputStream pos) {
        this.pos = pos;
    }
    @Override
    public void run() {
        try {
            pos.write("abcded".getBytes());
            pos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

}



0 0