001: /*
002: * ZipOutputFactory.java
003: *
004: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005: *
006: * Copyright 2002-2008, Thomas Kellerer
007: * No part of this code maybe reused without the permission of the author
008: *
009: * To contact the author please send an email to: support@sql-workbench.net
010: *
011: */
012: package workbench.util;
013:
014: import java.io.File;
015: import java.io.FileOutputStream;
016: import java.io.IOException;
017: import java.io.OutputStream;
018: import java.io.Writer;
019: import java.util.zip.ZipEntry;
020: import java.util.zip.ZipOutputStream;
021:
022: /**
023: *
024: * @author support@sql-workbench.net
025: */
026: public class ZipOutputFactory implements OutputFactory {
027: protected File archive;
028: protected OutputStream baseOut;
029: protected ZipOutputStream zout;
030: protected ZipEntry currentEntry;
031:
032: public ZipOutputFactory(File zip) {
033: this .archive = zip;
034: }
035:
036: private void initArchive() throws IOException {
037: baseOut = new FileOutputStream(archive);
038: zout = new ZipOutputStream(baseOut);
039: zout.setLevel(9);
040: }
041:
042: public boolean isArchive() {
043: return true;
044: }
045:
046: public OutputStream createOutputStream(File output)
047: throws IOException {
048: String filename = output.getName();
049: return createOutputStream(filename);
050: }
051:
052: public OutputStream createOutputStream(String filename)
053: throws IOException {
054: if (this .zout == null)
055: initArchive();
056:
057: this .currentEntry = new ZipEntry(filename);
058: this .zout.putNextEntry(currentEntry);
059: OutputStream out = new OutputStream() {
060: public void close() throws IOException {
061: zout.closeEntry();
062: currentEntry = null;
063: }
064:
065: public void flush() throws IOException {
066: zout.flush();
067: }
068:
069: public void write(byte[] b, int off, int len)
070: throws IOException {
071: zout.write(b, off, len);
072: }
073:
074: public void write(byte[] b) throws IOException {
075: zout.write(b);
076: }
077:
078: public void write(int b) throws IOException {
079: zout.write(b);
080: }
081: };
082: return out;
083: }
084:
085: public Writer createWriter(String output, String encoding)
086: throws IOException {
087: OutputStream out = createOutputStream(output);
088: return EncodingUtil.createWriter(out, encoding);
089: }
090:
091: public Writer createWriter(File output, String encoding)
092: throws IOException {
093: OutputStream out = createOutputStream(output);
094: return EncodingUtil.createWriter(out, encoding);
095: }
096:
097: public void done() throws IOException {
098: if (this.zout != null) {
099: zout.close();
100: }
101: if (baseOut != null) {
102: baseOut.close();
103: }
104: }
105:
106: }
|