1
22
23 package com.liferay.portal.kernel.zip;
24
25 import com.liferay.portal.kernel.io.FileCacheOutputStream;
26 import com.liferay.portal.kernel.log.Log;
27 import com.liferay.portal.kernel.log.LogFactoryUtil;
28 import com.liferay.portal.kernel.util.StringPool;
29
30 import java.io.BufferedInputStream;
31 import java.io.ByteArrayInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.Serializable;
35
36 import java.util.zip.ZipEntry;
37 import java.util.zip.ZipOutputStream;
38
39
44 public class ZipWriter implements Serializable {
45
46 public ZipWriter() throws IOException {
47 _fcos = new FileCacheOutputStream();
48 _zos = new ZipOutputStream(_fcos);
49 }
50
51 public void addEntry(String name, byte[] bytes) throws IOException {
52 addEntry(name, new ByteArrayInputStream(bytes));
53 }
54
55 public void addEntry(String name, InputStream is) throws IOException {
56 if (name.startsWith(StringPool.SLASH)) {
57 name = name.substring(1);
58 }
59
60 if (is == null) {
61 return;
62 }
63
64 if (_log.isDebugEnabled()) {
65 _log.debug("Adding " + name);
66 }
67
68 ZipEntry entry = new ZipEntry(name);
69
70 _zos.putNextEntry(entry);
71
72 BufferedInputStream bis = new BufferedInputStream(is, _BUFFER);
73
74 int count;
75
76 while ((count = bis.read(_data, 0, _BUFFER)) != -1) {
77 _zos.write(_data, 0, count);
78 }
79
80 bis.close();
81
82 _zos.closeEntry();
83 }
84
85 public void addEntry(String name, String s) throws IOException {
86 addEntry(name, s.getBytes());
87 }
88
89 public void addEntry(String name, StringBuilder sb) throws IOException {
90 addEntry(name, sb.toString());
91 }
92
93 public byte[] finish() throws IOException {
94 _zos.close();
95
96 return _fcos.getBytes();
97 }
98
99 public FileCacheOutputStream finishWithStream() throws IOException {
100 _zos.close();
101
102 return _fcos;
103 }
104
105 private static final Log _log = LogFactoryUtil.getLog(ZipWriter.class);
106
107 private static final int _BUFFER = 2048;
108
109 private FileCacheOutputStream _fcos;
110 private ZipOutputStream _zos;
111 private byte[] _data = new byte[_BUFFER];
112
113 }