OSDN Git Service

Add new source files
[armadillo/armadillo1.git] / src / jp / sfjp / armadillo / archive / zip / ZipArchiveCreator.java
1 package jp.sfjp.armadillo.archive.zip;
2
3 import java.io.*;
4 import jp.sfjp.armadillo.archive.*;
5 import jp.sfjp.armadillo.io.*;
6
7 public final class ZipArchiveCreator implements ArchiveCreator {
8
9     private ZipOutputStream os;
10
11     public ZipArchiveCreator(OutputStream os) {
12         this.os = new ZipOutputStream(os);
13     }
14
15     @Override
16     public ArchiveEntry newEntry(String name) {
17         return new ZipEntry(name);
18     }
19
20     @Override
21     public void addEntry(ArchiveEntry entry, File file) throws IOException {
22         if (file.isDirectory()) {
23             os.putNextEntry(toZipEntry(entry));
24             os.closeEntry();
25             entry.setAdded(true);
26         }
27         else
28             addEntry(entry, file, null, file.length());
29     }
30
31     @Override
32     public void addEntry(ArchiveEntry entry, InputStream is, long length) throws IOException {
33         addEntry(entry, null, is, length);
34     }
35
36     private void addEntry(ArchiveEntry entry, File file, InputStream src, final long length) throws IOException {
37         ZipEntry fileEntry = toZipEntry(entry);
38         fileEntry.setSize(length);
39         if (length == 0) {
40             fileEntry.setCompressedSize(0L);
41             fileEntry.method = ZipEntry.STORED;
42         }
43         os.putNextEntry(fileEntry);
44         if (length > 0) {
45             final long size;
46             InputStream is = (src == null) ? new FileInputStream(file) : src;
47             try {
48                 size = IOUtilities.transfer(is, os, length);
49             }
50             finally {
51                 if (src == null)
52                     is.close();
53             }
54             assert size == fileEntry.getSize() : "file size";
55             assert size == length : "file size";
56             entry.setSize(size);
57         }
58         os.closeEntry();
59         entry.setAdded(true);
60     }
61
62     static ZipEntry toZipEntry(ArchiveEntry entry) {
63         if (entry instanceof ZipEntry)
64             return (ZipEntry)entry;
65         ZipEntry newEntry = new ZipEntry(entry.getName());
66         entry.copyTo(newEntry);
67         if (newEntry.isDirectory())
68             newEntry.method = ZipEntry.STORED;
69         return newEntry;
70     }
71
72     @Override
73     public void close() throws IOException {
74         os.close();
75     }
76
77 }