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()
返回时,fileInputStream
和fileOutputStream
参数被关闭。但即使 fileInputStream
不会被关闭,它也不会再指向文件的开头(因为 fileCopy()
使用它从文件中读取字节)。在您的情况下,最简单的方法是当您想再次调用 fileCopy()
时创建一个新的 FileInputStream
。
关于java - 第二次传递给 java 中的函数时 FileInputStream 被关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508743/