OSDN Git Service

Add new source files
[armadillo/armadillo1.git] / src / jp / sfjp / armadillo / archive / lzh / LzhOutputStream.java
1 package jp.sfjp.armadillo.archive.lzh;
2
3 import java.io.*;
4 import jp.sfjp.armadillo.archive.*;
5 import jp.sfjp.armadillo.compression.lzhuf.*;
6 import jp.sfjp.armadillo.io.*;
7
8 public final class LzhOutputStream extends ArchiveOutputStream {
9
10     private LzhHeader header;
11     private LzhEntry ongoingEntry;
12     private InspectionOutputStream ios;
13     private LzhChecksum crc;
14     private ByteArrayOutputStream bos;
15
16     public LzhOutputStream(OutputStream os) {
17         super(os);
18         this.header = new LzhHeader();
19         this.crc = new LzhChecksum();
20         this.bos = new ByteArrayOutputStream();
21     }
22
23     public void putNextEntry(LzhEntry entry) throws IOException {
24         if (ongoingEntry != null)
25             closeEntry();
26         ongoingEntry = entry;
27         LzhMethod method = entry.getMethod();
28         crc.reset();
29         bos.reset();
30         frontStream = ios = new InspectionOutputStream(openStream(bos, method), crc);
31     }
32
33     static OutputStream openStream(OutputStream os, LzhMethod method) {
34         if (method.isCompressing())
35             return new LzssOutputStream(new LzhHuffmanEncoder(os, method.getThreshold()),
36                                         method.getDictionarySize(),
37                                         method.getMatchSize(),
38                                         method.getThreshold());
39         else
40             return os;
41     }
42
43     public void closeEntry() throws IOException {
44         frontStream.flush();
45         if (frontStream != out)
46             frontStream.close();
47         frontStream = out;
48         if (ios != null) {
49             ongoingEntry.compressedSize = bos.size();
50             ongoingEntry.crc = getCrc();
51         }
52         writeHeader(ongoingEntry);
53         if (ios != null)
54             bos.writeTo(out);
55         ongoingEntry = null;
56         ios = null;
57         crc.reset();
58         bos.reset();
59     }
60
61     public void writeHeader(LzhEntry entry) throws IOException {
62         header.write(out, entry);
63     }
64
65     public void writeHeader(LzhEntry entry, OutputStream os) throws IOException {
66         header.write(os, entry);
67     }
68
69     public short getCrc() {
70         return crc.getShortValue();
71     }
72
73     @Override
74     public void close() throws IOException {
75         try {
76             flush();
77             super.write(0); // end of archive
78             super.flush();
79         }
80         finally {
81             header = null;
82             ongoingEntry = null;
83             ios = null;
84             crc = null;
85             bos = null;
86             super.close();
87         }
88     }
89
90 }