[javaSE] IO流(管道流)

之前我们使用io流,都是需要一个中间数组,管道流可以直接输入流对接输出流,一般和多线程配合使用,当读取流中没数据时会阻塞当前的线程,对其他线程没有影响

定义一个类Read实现Runable接口,实现run()方法,构造方法传递PipedInputStream对象

读取流里面的数据

定义一个类Write实现Runable接口,实现run()方法,构造方法传递PipedOutputStream对象

写入流里面数据

获取PipedInputStream对象,new出来

获取PipedOutputStream对象,new出来

调用PipedInputStream对象的connect()方法,对接输出流,参数:PipedOutputStream对象

开启两个线程执行读写

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
 * 读取数据线程
 * @author taoshihan
 *
 */
class ReadPipe implements Runnable{
    private PipedInputStream in;
    public ReadPipe(PipedInputStream in) {
        this.in=in;
    }
    @Override
    public void run() {
        System.out.println("开始读取。。。如果没有数据会阻塞");
        byte[] b=new byte[1024];
        try {
            int len=in.read(b);
            String info=new String(b,0,len);
            in.close();
            System.out.println(info);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
/**
 * 写入数据线程
 * @author taoshihan
 *
 */
class WritePipe implements Runnable{
    private PipedOutputStream out;
    public WritePipe(PipedOutputStream out) {
        this.out=out;
    }
    @Override
    public void run() {
        System.out.println("开始写入。。。延迟5秒");
        try {
            Thread.sleep(5000);
            out.write("我是数据".getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
}
public class PipeDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        //连接管道
        PipedInputStream in=new PipedInputStream();
        PipedOutputStream out=new PipedOutputStream();
        in.connect(out);
        //开启线程
        new Thread(new ReadPipe(in)).start();
        new Thread(new WritePipe(out)).start();
    }

}

原文地址:https://www.cnblogs.com/taoshihan/p/5566179.html