第二次传递给java中的函数时,FileInputStream正在关闭

时间:2014-10-22 13:34:47

标签: java fileinputstream

 public static void main(String[] args){
        try{
            FileInputStream fileInputStream=new FileInputStream("sourcefile.txt");
            File file1=new File("copy1.txt");
            File file2=new File("copy2.txt");
            //firstcopy
            FileOutputStream fileOutputStream1=new FileOutputStream(file1);
            fileCopy(fileInputStream, fileOutputStream1);
            fileOutputStream1.close();
            //secondcopy
            FileOutputStream fileOutputStream2=new FileOutputStream(file2);
            fileCopy(fileInputStream, fileOutputStream2); 
            fileOutputStream2.close();

        }catch(FileNotFoundException fileNotFoundException){
            System.err.println(fileNotFoundException.getMessage());
            fileNotFoundException.printStackTrace();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }

    }
    //file copy function
    public static void fileCopy(FileInputStream fileInputStream,FileOutputStream fileOutputStream) throws IOException{
        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes 
        while ((length = fileInputStream.read(buffer)) > 0){

            fileOutputStream.write(buffer, 0, length);

        }

        fileInputStream.close();
        fileOutputStream.close();

        System.out.println("File is copied successful!");
    }
Output:
    File is copied successful!
    java.io.IOException: Stream Closed
        at java.io.FileInputStream.readBytes(Native Method)
        at java.io.FileInputStream.read(FileInputStream.java:243)
        at FileCopier.fileCopy(FileCopier.java:38)
        at FileCopier.main(FileCopier.java:21)

为什么我的第二次检查不起作用? 当我直接传递"new FileInputStream("sourcefile.txt")"而不是fileInputsteam对象时,它正在工作。

1 个答案:

答案 0 :(得分:5)

因为您的fileCopy()方法明确关闭了它。

您将fileInputStream传递给fileCopy()

fileCopy(fileInputStream, fileOutputStream1);

fileCopy()内:

fileInputStream.close();

fileCopy()返回时,fileInputStreamfileOutputStream参数将被关闭。但即使fileInputStream不会被关闭,也不会再指向文件的开头(因为fileCopy()使用它来从文件中读取字节)。最简单的方法是,当您想再次呼叫FileInputStream时,只需创建一个新的fileCopy()