[javaSE] IO流(管道流)

前端之家收集整理的这篇文章主要介绍了[javaSE] IO流(管道流)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

 

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

读取流里面的数据

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

写入流里面数据

 

获取PipedInputStream对象,new出来

获取PipedOutputStream对象,new出来

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

 

开启两个线程执行读写

import java.io.IOException;
 java.io.PipedInputStream;
 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();
        }
    }
    
}

 * 写入数据线程
 * class WritePipe  PipedOutputStream out;
     WritePipe(PipedOutputStream out) {
        this.out=out;
    }
    @Override
     run() {
        System.out.println("开始写入。。。延迟5秒" {
            Thread.sleep(5000);
            out.write("我是数据".getBytes());
            out.close();
        }  (Exception e) {
            e.printStackTrace();
        }
        
    }
    
}
class PipeDemo {

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

}

猜你在找的Java SE相关文章