java——管道流的使用方法

2019年2月22日23:58:34 发表评论 1,550 views
import java.io.*;
public class pipedstreamdemo {
//本案例需要背默
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        try{
            Sender sender = new Sender();//产生两个线程对象
            Receiver receiver = new Receiver();
            PipedOutputStream out = sender.getOutputStream();//写入
            PipedInputStream in = receiver.getInputStream();//读出
            out.connect(in);//将输出发送到输入
            sender.start();//启动线程
            receiver.start();
        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }

    }

}
class Sender extends Thread
{
    private PipedOutputStream out = new PipedOutputStream();
    public PipedOutputStream getOutputStream()
    {
        return out;
    }
    public void run()
    {
        String s = new String("Receiver,你好!");
        try{
            out.write(s.getBytes());//写入(发送)
            out.close();
        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}
class Receiver extends Thread
{
    private PipedInputStream in = new PipedInputStream();//此处含义是???
    public PipedInputStream getInputStream()
    {
        return in;
    }
    public void run()
    {
        String s = null;
        byte[] buf = new byte[1024];
        try{
            int len = in.read(buf);//读出数据
            s = new String(buf,0,len);
            System.out.println("收到了以下信息:"+s);
            in.close();
        }
        catch(IOException e){
            System.out.print(e.getMessage());
        }
    }
}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: