项目场景:
利用 java.util.zip 的相关的类进行zip 包导出的操作,结果出现 zip 包只导出了一个文件
问题描述:
报错 stream closeed
错误日志:
java.io.IOException: Stream closed
at java.util.zip.ZipOutputStream.ensureOpen(ZipOutputStream.java:97)
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:190)
at com.cyl.base.util.ZipFileUtil.writeFile2(ZipFileUtil.java:79)
at com.cyl.base.util.ZipFileUtil.writeFile(ZipFileUtil.java:53)
at com.cyl.base.util.ZipFileUtil.writeZipFile(ZipFileUtil.java:31)
at com.base.test.ZipFileUtilTest.testWrite(ZipFileUtilTest.java:28)
原因分析:
在这个方法中 传入 的 zos没有被关闭,关闭了 zos 的封装流 Writer fos, 导致了 zos也被标记为已关闭。所以报错
private void copyFile(File file, ZipOutputStream zos) throws IOException {
FileInputStream is = null;
Writer fos = new OutputStreamWriter(zos);
try {
is = new FileInputStream(file);
byte[] bytes = new byte[1024];
char[] chars = new char[1024];
int length;
while ((length = is.read(bytes)) > 0) {
for (int i = 0; i < length; i++) {
chars[i] = (char) bytes[i];
}
fos.write(chars, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}
}
try {
fos.close();
} catch (Exception e) {
}
}
}
解决方案:
Writer fos 由外层调用方法创建,由外层方法关闭
public void writeFile (List<File> files, File zipFile) throws IOException {
ZipOutputStream zos = null;
FileOutputStream fos = null;
Writer writer = null;
try {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
writer = new OutputStreamWriter(zos);
// 2. 循环创建目录,写入文件
for (File file: files) {
copyFile(file, writer);
}
} catch (IOException e) {
throw e;
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
}
}
}
}
private void copyFile(File file, Writer fos) throws IOException {
FileInputStream is = null;
try {
is = new FileInputStream(file);
byte[] bytes = new byte[1024];
char[] chars = new char[1024];
int length;
while ((length = is.read(bytes)) > 0) {
for (int i = 0; i < length; i++) {
chars[i] = (char) bytes[i];
}
fos.write(chars, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}
}
}
}