java - 第二次传递给 java 中的函数时 FileInputStream 被关闭

标签 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 对象时,它正在工作。

最佳答案

因为您的 fileCopy() 方法显式关闭了它。

fileInputStream传递给fileCopy():

fileCopy(fileInputStream, fileOutputStream1);

fileCopy()内部:

fileInputStream.close();

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

关于java - 第二次传递给 java 中的函数时 FileInputStream 被关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508743/

相关文章:

java - java applet 的 PKI 标准

java - Maven 与自定义资源共享模块中的源

java - Java-在线播放来自已读取InputStream的音频

java - 如何在输入流中写入

java - EOF 处的空指针异常

java - 如何使用 View 和过滤器避免 hibernate 中的嵌套查询

java - 如何设置Textarea的最大行数

java inputStream一次只读取一个标签

android - 无法打开 FileInputStream

android - XmlPullParser.getInputEncoding() 在 API11+ 和 Android 的 API11 之前版本上的不同行为