下面代码可以实现,在Write的run方法中加入读取文件的流。代码优化的话,你可以在new Write对象的时候传入参数,比如你要读取哪个文件,
- import java.io.*;
- class Read implements Runnable
- {
- private PipedInputStream in;
- Read(PipedInputStream in)
- {
- this.in = in;
- }
- public void run()
- {
- try
- {
- byte[] buf = new byte[1024];
- //System.out.println("读取前。。没有数据阻塞");
- int len = 0;
- //System.out.println("读到数据。。阻塞结束");
- while ((len=in.read(buf))!=-1)
- {
- String s= new String(buf,0,len);
- System.out.println(s);
- }
- in.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("管道读取流失败");
- }
- }
- }
- class Write implements Runnable
- {
- private PipedOutputStream out;
- Write(PipedOutputStream out)
- {
- this.out = out;
- }
- public void run()
- {
- try
- {
- FileInputStream fis=new FileInputStream("d:\\2.java");
- byte[] b=new byte[1024];
- int len=0;
- while ((len=fis.read(b))!=-1)
- {
- out.write(b,0,len);
- }
- fis.close();
- out.close();
- }
- catch (Exception e)
- {
- throw new RuntimeException("管道输出流失败");
- }
- }
- }
- class PipedStreamDemo
- {
- public static void main(String[] args) throws IOException
- {
- PipedInputStream in = new PipedInputStream();
- PipedOutputStream out = new PipedOutputStream();
- in.connect(out);
- Read r = new Read(in);
- Write w = new Write(out);
- new Thread(r).start();
- new Thread(w).start();
- }
- }
复制代码 |