Search code examples
javafileinputstream

FileInputStream is getting closed when passing second time to a function in java


 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)

Why my secondcopy is not working? It is working when I am passing "new FileInputStream("sourcefile.txt")" directly instead of fileInputsteam object.


Solution

  • Because your fileCopy() method explicitly closes it.

    You pass fileInputStream to fileCopy():

    fileCopy(fileInputStream, fileOutputStream1);
    

    And inside fileCopy():

    fileInputStream.close();
    

    When fileCopy() returns, the fileInputStream and fileOutputStream parameters are closed. But even if fileInputStream would not be closed, it would not point to the beginning of the file anymore (because fileCopy() uses it to read bytes from the file). Easiest in your case is to just create a new FileInputStream when you want to call fileCopy() again.