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