【发布时间】:2018-06-22 08:19:56
【问题描述】:
即使我没有关闭任何流,我的 zipInputStream 在写入第一个文件本身后也会关闭。
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
modelFolderName = <somefoldername>
modelFileName = <somefilename>
String FILE_STORAGE_LOCATION = env.getProperty("workspacePath");
File folder = new File(FILE_STORAGE_LOCATION + "/" + modelFolderName );
if(!folder.exists()) {
folder.mkdirs();
}
try (FileOutputStream fout=new FileOutputStream(FILE_STORAGE_LOCATION + "/" + modelFolderName + "/" + modelFileName)) {
try (BufferedInputStream in = new BufferedInputStream(zipInputStream)) {
byte[] buffer = new byte[8096];
while (true) {
int count = in.read(buffer);
if (count == -1) {
break;
}
fout.write(buffer, 0, count);
}
}
}
zipEntry = zipInputStream.getNextEntry();
}
【问题讨论】:
-
您是否缺少代码?因为您只检查第一个流条目。循环遍历 zipEntries,而不仅仅是一个条目
-
在您的第二次尝试资源中,您将
zipInputStream包装到BufferedInputStream中,该BufferedInputStream在尝试后关闭并关闭也用于zipInputStream的底层流 -
此外,您似乎正在使用 try 块内的整个流,而不仅仅是条目
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建 minimal reproducible example。使用edit 链接改进您的问题 - 不要通过 cmets 添加更多信息。谢谢!
-
不要只将异常消息放在问题的标题中。将异常堆栈跟踪的相关部分添加到问题中,并清楚地确定您的代码抛出了哪一行。
标签: java fileoutputstream zipinputstream