public void methodCopy() throws Exception{
File file1=new File("C:\\Users\\Liu\\Desktop\\【必看】资料来源.txt");
File file2=new File("C:\\Users\\Liu\\Desktop\\【必看】资料来源1.txt");
//1.使用字节流实现文本文件的复制
FileInputStream fis=new FileInputStream(file1);
FileOutputStream fos=new FileOutputStream(file2);
    InputStreamReader read=new InputStreamReader(fis);
    BufferedReader br=new BufferedReader(read);
    OutputStreamWriter write=new OutputStreamWriter(fos);
    BufferedWriter bw=new BufferedWriter(write);
    char[] c=new char[1024];
   
    int len;
    while((len=read.read(c))!=-1){
     bw.write(c, 0, len);
     bw.flush();
     if(fos!=null){
    
     bw.close();
     }
     if(fis!=null){
    
     br.close();
     }
    }
}
Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamDecoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.Reader.read(Unknown Source)
at at.xupt.liu.FileCopy.methodCopy(TestFileCopy.java:35)
at at.xupt.liu.TestFileCopy.main(TestFileCopy.java:17)

解决方案 »

  1.   

    关闭流的操作操作应该是在对该流的全部操作完成之后.你上面的代码在while循环的第一次就关闭了流,那么第二次使用的时候就会报错的了.一般用try-catch操作放在finally块中处理或者对于JDK1.7后放在带括号的try中自动关闭.
      

  2.   

    while((len=read.read(c))!=-1)
         bw.write(c, 0, len);
        bw.flush();
        if(fos!=null){
        bw.close();
    }