JAVA中管道Piped输入输出流

管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同之处在于,它主要用于线程之间的数据传输,而传输的媒介为内存。
管道输入/输出流主要包括了如下4中具体实现:PipedOutputStream, PipedInputStream,PipedReader, PipedWriter,前两种面向字节,后面两种面向字符。

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
**管道流中必须先进行绑定,也就是调用connect()方法,如果没有输入/输出流绑定起来,对于该流的访问讲会抛出异常**
/*管道流要用到线程的知识
 * 
 * /
 */
class write implements Runnable{
    private PipedOutputStream out = null;
    public void run() {
        String s = "abc";
        try {
            out.write(s.getBytes());
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }
    write(PipedOutputStream out){
        this.out = out;
    }
}
class read implements Runnable{
    private PipedInputStream in = null;
    public void run() { 
        byte[] buf = new byte[1024];
        try {
            int len = in.read(buf);
            String s=new String(buf,0,len);
            System.out.println(s);
            in.close();
        }catch (IOException e) {    
            e.printStackTrace();
        }
    }
    read(PipedInputStream in){
        this.in=in; 
    }   
}

public class guandaodemo {
    public static void main(String args[]) throws IOException{


        PipedOutputStream out= new PipedOutputStream(); 
        PipedInputStream in=new PipedInputStream ();
        out.connect(in);//--------------------->>>>>>>>>>管道流的重点语句
        write w=new write(out);
        read r=new read(in);

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start(); 
    }
}
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
class writer implements Runnable{
    private PipedWriter out = null;
    public void run() {
        String s = "abc";
        try {
            out.write(s);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }
    writer(PipedWriter out){
        this.out = out;
    }
}
class read implements Runnable{
    private PipedReader in = null;
    public void run() { 
        try {
            int receive = 0;
            while ((receive = in.read()) != -1) {
                System.out.print((char)receive);
            }
            in.close();
        }catch (IOException e) {    
            e.printStackTrace();
        }
    }
    read(PipedReader in){
        this.in = in;   
    }   
}
public class PipedDemo  {
    public static void main(String args[]) throws IOException{
        PipedWriter out = new PipedWriter(); 
        PipedReader in = new PipedReader();
        out.connect(in);//--------------------->>>>>>>>>>管道流的重点语句
        writer w = new writer(out);
        read r = new read(in);
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start(); 
    }
}

你可能感兴趣的:(Java编程精华)