对于生成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(); } |
本文探讨了在Java中使用ZipOutputStream时遇到的System closed错误,通常发生在尝试第二次putNextEntry时。文章提供了两种解决方案:一是通过OutputStreamWriter包装并重写close方法;二是使用ByteArrayOutputStream避免流被关闭。
1132

被折叠的 条评论
为什么被折叠?



