对于生成zip文件,一般在第二次putNextEntry时会报错:System closed,原因是一般的流都会自动调用close()方法,关闭流,所以在第二次调用putNextEntry时会因为流被关闭报错。有两种解决办法:
1、用OutputStreamWriter包装一下,并且重写close方法;
2、将流放入到ByteArrayOutputStream 内存中,这样就不会close了
ZipInputStream同理
用OutputStreamWriter包装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 用OutputStreamWriter包装: Path path = Paths.get("target/output/jackson/Jackson.zip"); try { Files.createDirectories(path.getParent()); } catch (IOException e) { e.printStackTrace(); } try( OutputStream out = new FileOutputStream(path.toFile()); ZipOutputStream zo = new ZipOutputStream(out); ){ for (Map.Entry<String, Object> e: map.entrySet()) { zo.putNextEntry(new ZipEntry(e.getKey())); objectMapper.writeValue(new OutputStreamWriter(zo, "UTF-8"){ @Override public void close() throws IOException { flush(); } }, e.getValue()); System.out.println("生成成功:"+e.getKey()); }
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } |
用ByteArrayOutputStream 包装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Path path = Paths.get("target/output/jackson/Jackson.zip"); try { Files.createDirectories(path.getParent()); } catch (IOException e) { e.printStackTrace(); } try( OutputStream out = new FileOutputStream(path.toFile()); ZipOutputStream zo = new ZipOutputStream(out); ){ for (Map.Entry<String, Object> e: map.entrySet()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); zo.putNextEntry(new ZipEntry(e.getKey())); objectMapper.writeValue(baos, e.getValue()); baos.writeTo(zo); baos.close(); System.out.println("生成成功:"+e.getKey()); }
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } |