当前位置:编程学习 > JAVA >>

java中PipedOutputStream和PipedInputStream类用法

ipedOutputStream和PipedInputStream用于在应用程序中创建管道通信

实例:

[java]
import java.io.*; 
 
public class PipedStreamTest { 
    public static void main(String [] args) { 
        Sender sender = new Sender(); 
        Receiver receiver = new Receiver(); 
         
        PipedOutputStream outStream = sender.getOutStream(); 
        PipedInputStream inStream = receiver.getInStream(); 
         
        try { 
            //inStream.connect(outStream); // 与下一句一样 
            outStream.connect(inStream); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
         
        sender.start(); 
        receiver.start(); 
    } 

 
class Sender extends Thread { 
    private PipedOutputStream outStream = new PipedOutputStream(); 
     
    public PipedOutputStream getOutStream() { 
        return outStream; 
    } 
     
    public void run() { 
        String info = "hello, receiver"; 
         
        try { 
            outStream.write(info.getBytes()); 
             
            outStream.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

 
class Receiver extends Thread { 
    private PipedInputStream inStream = new PipedInputStream(); 
     
    public PipedInputStream getInStream() { 
        return inStream; 
    } 
     
    public void run() { 
        byte[] buf = new byte[1024]; 
         
        try { 
            int len = inStream.read(buf); 
             
            System.out.println("receive message from sender : " + new String(buf, 0, len)); 
             
            inStream.close(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    }    

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,