你的顺序有点问题,其他都没问题,主要是应该用FileInputStream嘛,你用错了。
首先是从管道的写流中把文件写入;再从管道读取流把文件读取;
管道流的写入流用FileInputStream ();而管道的读取流又用到了FileOutputStream ();
一共四个流,可能有异常,由于管道写流结束导致;但文件复制一定能完成!- package cn.itcast.demo;
- import java.io.*;
- public class Piped {
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- PipedInputStream in = new PipedInputStream();
- PipedOutputStream out = new PipedOutputStream();
- Writer w = new Writer(out);
- Read r = new Read(in);
- in.connect(out);
- new Thread(r).start();
- new Thread(w).start();
-
- }
- }
- class Read implements Runnable{
- private PipedInputStream in;
- Read(PipedInputStream in){
- this.in = in;
- }
- public void run(){
- try{
- FileOutputStream fis = new FileOutputStream("D:\\pipe2.txt");
- byte[] buf = new byte[1024];
- int len = 0;
- while((len = in.read(buf))!= -1)
- {
- fis.write(buf, 0, len);
- }
- fis.flush();
- }
- catch(Exception e){
- System.out.println("管道流读取失败"+e.getMessage());
- }
- }
- }
- class Writer implements Runnable{
- private PipedOutputStream out ;
- Writer(PipedOutputStream out){
- this.out = out;
- }
-
- public void run(){
-
- try{
- FileInputStream fi=new FileInputStream("D:\\pipe.txt");
- byte[] off=new byte[1024];
- int len=0;
- while((len=fi.read(off))!=-1)
- {
- out.write(off,0,len);
- }
-
-
- }
- catch(Exception e){
- System.out.println("管道流写入失败");
- }
-
-
- }
-
- }
复制代码 |