ZipOutputStream.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /* ZipOutputStream.java --
  2. Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util.zip;
  32. import java.io.IOException;
  33. import java.io.OutputStream;
  34. import java.io.UnsupportedEncodingException;
  35. import java.util.Enumeration;
  36. import java.util.Vector;
  37. /**
  38. * This is a FilterOutputStream that writes the files into a zip
  39. * archive one after another. It has a special method to start a new
  40. * zip entry. The zip entries contains information about the file name
  41. * size, compressed size, CRC, etc.
  42. *
  43. * It includes support for STORED and DEFLATED entries.
  44. *
  45. * This class is not thread safe.
  46. *
  47. * @author Jochen Hoenicke
  48. */
  49. public class ZipOutputStream extends DeflaterOutputStream implements ZipConstants
  50. {
  51. private Vector entries = new Vector();
  52. private CRC32 crc = new CRC32();
  53. private ZipEntry curEntry = null;
  54. private int curMethod;
  55. private int size;
  56. private int offset = 0;
  57. private byte[] zipComment = new byte[0];
  58. private int defaultMethod = DEFLATED;
  59. /**
  60. * Our Zip version is hard coded to 1.0 resp. 2.0
  61. */
  62. private static final int ZIP_STORED_VERSION = 10;
  63. private static final int ZIP_DEFLATED_VERSION = 20;
  64. /**
  65. * Compression method. This method doesn't compress at all.
  66. */
  67. public static final int STORED = 0;
  68. /**
  69. * Compression method. This method uses the Deflater.
  70. */
  71. public static final int DEFLATED = 8;
  72. /**
  73. * Creates a new Zip output stream, writing a zip archive.
  74. * @param out the output stream to which the zip archive is written.
  75. */
  76. public ZipOutputStream(OutputStream out)
  77. {
  78. super(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true));
  79. }
  80. /**
  81. * Set the zip file comment.
  82. * @param comment the comment.
  83. * @exception IllegalArgumentException if encoding of comment is
  84. * longer than 0xffff bytes.
  85. */
  86. public void setComment(String comment)
  87. {
  88. byte[] commentBytes;
  89. try
  90. {
  91. commentBytes = comment.getBytes("UTF-8");
  92. }
  93. catch (UnsupportedEncodingException uee)
  94. {
  95. throw new AssertionError(uee);
  96. }
  97. if (commentBytes.length > 0xffff)
  98. throw new IllegalArgumentException("Comment too long.");
  99. zipComment = commentBytes;
  100. }
  101. /**
  102. * Sets default compression method. If the Zip entry specifies
  103. * another method its method takes precedence.
  104. * @param method the method.
  105. * @exception IllegalArgumentException if method is not supported.
  106. * @see #STORED
  107. * @see #DEFLATED
  108. */
  109. public void setMethod(int method)
  110. {
  111. if (method != STORED && method != DEFLATED)
  112. throw new IllegalArgumentException("Method not supported.");
  113. defaultMethod = method;
  114. }
  115. /**
  116. * Sets default compression level. The new level will be activated
  117. * immediately.
  118. * @exception IllegalArgumentException if level is not supported.
  119. * @see Deflater
  120. */
  121. public void setLevel(int level)
  122. {
  123. def.setLevel(level);
  124. }
  125. /**
  126. * Write an unsigned short in little endian byte order.
  127. */
  128. private void writeLeShort(int value) throws IOException
  129. {
  130. out.write(value & 0xff);
  131. out.write((value >> 8) & 0xff);
  132. }
  133. /**
  134. * Write an int in little endian byte order.
  135. */
  136. private void writeLeInt(int value) throws IOException
  137. {
  138. writeLeShort(value);
  139. writeLeShort(value >> 16);
  140. }
  141. /**
  142. * Write a long value as an int. Some of the zip constants
  143. * are declared as longs even though they fit perfectly well
  144. * into integers.
  145. */
  146. private void writeLeInt(long value) throws IOException
  147. {
  148. writeLeInt((int) value);
  149. }
  150. /**
  151. * Starts a new Zip entry. It automatically closes the previous
  152. * entry if present. If the compression method is stored, the entry
  153. * must have a valid size and crc, otherwise all elements (except
  154. * name) are optional, but must be correct if present. If the time
  155. * is not set in the entry, the current time is used.
  156. * @param entry the entry.
  157. * @exception IOException if an I/O error occured.
  158. * @exception ZipException if stream was finished.
  159. */
  160. public void putNextEntry(ZipEntry entry) throws IOException
  161. {
  162. if (entries == null)
  163. throw new ZipException("ZipOutputStream was finished");
  164. int method = entry.getMethod();
  165. int flags = 0;
  166. if (method == -1)
  167. method = defaultMethod;
  168. if (method == STORED)
  169. {
  170. if (entry.getCompressedSize() >= 0)
  171. {
  172. if (entry.getSize() < 0)
  173. entry.setSize(entry.getCompressedSize());
  174. else if (entry.getSize() != entry.getCompressedSize())
  175. throw new ZipException
  176. ("Method STORED, but compressed size != size");
  177. }
  178. else
  179. entry.setCompressedSize(entry.getSize());
  180. if (entry.getSize() < 0)
  181. throw new ZipException("Method STORED, but size not set");
  182. if (entry.getCrc() < 0)
  183. throw new ZipException("Method STORED, but crc not set");
  184. }
  185. else if (method == DEFLATED)
  186. {
  187. if (entry.getCompressedSize() < 0
  188. || entry.getSize() < 0 || entry.getCrc() < 0)
  189. flags |= 8;
  190. }
  191. if (curEntry != null)
  192. closeEntry();
  193. if (entry.getTime() < 0)
  194. entry.setTime(System.currentTimeMillis());
  195. entry.flags = flags;
  196. entry.offset = offset;
  197. entry.setMethod(method);
  198. curMethod = method;
  199. /* Write the local file header */
  200. writeLeInt(LOCSIG);
  201. writeLeShort(method == STORED
  202. ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
  203. writeLeShort(flags);
  204. writeLeShort(method);
  205. writeLeInt(entry.getDOSTime());
  206. if ((flags & 8) == 0)
  207. {
  208. writeLeInt((int)entry.getCrc());
  209. writeLeInt((int)entry.getCompressedSize());
  210. writeLeInt((int)entry.getSize());
  211. }
  212. else
  213. {
  214. writeLeInt(0);
  215. writeLeInt(0);
  216. writeLeInt(0);
  217. }
  218. byte[] name;
  219. try
  220. {
  221. name = entry.getName().getBytes("UTF-8");
  222. }
  223. catch (UnsupportedEncodingException uee)
  224. {
  225. throw new AssertionError(uee);
  226. }
  227. if (name.length > 0xffff)
  228. throw new ZipException("Name too long.");
  229. byte[] extra = entry.getExtra();
  230. if (extra == null)
  231. extra = new byte[0];
  232. writeLeShort(name.length);
  233. writeLeShort(extra.length);
  234. out.write(name);
  235. out.write(extra);
  236. offset += LOCHDR + name.length + extra.length;
  237. /* Activate the entry. */
  238. curEntry = entry;
  239. crc.reset();
  240. if (method == DEFLATED)
  241. def.reset();
  242. size = 0;
  243. }
  244. /**
  245. * Closes the current entry.
  246. * @exception IOException if an I/O error occured.
  247. * @exception ZipException if no entry is active.
  248. */
  249. public void closeEntry() throws IOException
  250. {
  251. if (curEntry == null)
  252. throw new ZipException("No open entry");
  253. /* First finish the deflater, if appropriate */
  254. if (curMethod == DEFLATED)
  255. super.finish();
  256. int csize = curMethod == DEFLATED ? def.getTotalOut() : size;
  257. if (curEntry.getSize() < 0)
  258. curEntry.setSize(size);
  259. else if (curEntry.getSize() != size)
  260. throw new ZipException("size was "+size
  261. +", but I expected "+curEntry.getSize());
  262. if (curEntry.getCompressedSize() < 0)
  263. curEntry.setCompressedSize(csize);
  264. else if (curEntry.getCompressedSize() != csize)
  265. throw new ZipException("compressed size was "+csize
  266. +", but I expected "+curEntry.getSize());
  267. if (curEntry.getCrc() < 0)
  268. curEntry.setCrc(crc.getValue());
  269. else if (curEntry.getCrc() != crc.getValue())
  270. throw new ZipException("crc was " + Long.toHexString(crc.getValue())
  271. + ", but I expected "
  272. + Long.toHexString(curEntry.getCrc()));
  273. offset += csize;
  274. /* Now write the data descriptor entry if needed. */
  275. if (curMethod == DEFLATED && (curEntry.flags & 8) != 0)
  276. {
  277. writeLeInt(EXTSIG);
  278. writeLeInt((int)curEntry.getCrc());
  279. writeLeInt((int)curEntry.getCompressedSize());
  280. writeLeInt((int)curEntry.getSize());
  281. offset += EXTHDR;
  282. }
  283. entries.addElement(curEntry);
  284. curEntry = null;
  285. }
  286. /**
  287. * Writes the given buffer to the current entry.
  288. * @exception IOException if an I/O error occured.
  289. * @exception ZipException if no entry is active.
  290. */
  291. public void write(byte[] b, int off, int len) throws IOException
  292. {
  293. if (curEntry == null)
  294. throw new ZipException("No open entry.");
  295. switch (curMethod)
  296. {
  297. case DEFLATED:
  298. super.write(b, off, len);
  299. break;
  300. case STORED:
  301. out.write(b, off, len);
  302. break;
  303. }
  304. crc.update(b, off, len);
  305. size += len;
  306. }
  307. /**
  308. * Finishes the stream. This will write the central directory at the
  309. * end of the zip file and flush the stream.
  310. * @exception IOException if an I/O error occured.
  311. */
  312. public void finish() throws IOException
  313. {
  314. if (entries == null)
  315. return;
  316. if (curEntry != null)
  317. closeEntry();
  318. int numEntries = 0;
  319. int sizeEntries = 0;
  320. Enumeration e = entries.elements();
  321. while (e.hasMoreElements())
  322. {
  323. ZipEntry entry = (ZipEntry) e.nextElement();
  324. int method = entry.getMethod();
  325. writeLeInt(CENSIG);
  326. writeLeShort(method == STORED
  327. ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
  328. writeLeShort(method == STORED
  329. ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
  330. writeLeShort(entry.flags);
  331. writeLeShort(method);
  332. writeLeInt(entry.getDOSTime());
  333. writeLeInt((int)entry.getCrc());
  334. writeLeInt((int)entry.getCompressedSize());
  335. writeLeInt((int)entry.getSize());
  336. byte[] name;
  337. try
  338. {
  339. name = entry.getName().getBytes("UTF-8");
  340. }
  341. catch (UnsupportedEncodingException uee)
  342. {
  343. throw new AssertionError(uee);
  344. }
  345. if (name.length > 0xffff)
  346. throw new ZipException("Name too long.");
  347. byte[] extra = entry.getExtra();
  348. if (extra == null)
  349. extra = new byte[0];
  350. String str = entry.getComment();
  351. byte[] comment;
  352. try
  353. {
  354. comment = str != null ? str.getBytes("UTF-8") : new byte[0];
  355. }
  356. catch (UnsupportedEncodingException uee)
  357. {
  358. throw new AssertionError(uee);
  359. }
  360. if (comment.length > 0xffff)
  361. throw new ZipException("Comment too long.");
  362. writeLeShort(name.length);
  363. writeLeShort(extra.length);
  364. writeLeShort(comment.length);
  365. writeLeShort(0); /* disk number */
  366. writeLeShort(0); /* internal file attr */
  367. writeLeInt(0); /* external file attr */
  368. writeLeInt(entry.offset);
  369. out.write(name);
  370. out.write(extra);
  371. out.write(comment);
  372. numEntries++;
  373. sizeEntries += CENHDR + name.length + extra.length + comment.length;
  374. }
  375. writeLeInt(ENDSIG);
  376. writeLeShort(0); /* disk number */
  377. writeLeShort(0); /* disk with start of central dir */
  378. writeLeShort(numEntries);
  379. writeLeShort(numEntries);
  380. writeLeInt(sizeEntries);
  381. writeLeInt(offset);
  382. writeLeShort(zipComment.length);
  383. out.write(zipComment);
  384. out.flush();
  385. entries = null;
  386. }
  387. }