OSDN Git Service

Add new source files
[armadillo/armadillo1.git] / src / jp / sfjp / armadillo / archive / cab / CabArchiveCreator.java
diff --git a/src/jp/sfjp/armadillo/archive/cab/CabArchiveCreator.java b/src/jp/sfjp/armadillo/archive/cab/CabArchiveCreator.java
new file mode 100644 (file)
index 0000000..a8fc27c
--- /dev/null
@@ -0,0 +1,64 @@
+package jp.sfjp.armadillo.archive.cab;
+
+import java.io.*;
+import jp.sfjp.armadillo.archive.*;
+import jp.sfjp.armadillo.io.*;
+
+public final class CabArchiveCreator implements ArchiveCreator {
+
+    private CabOutputStream os;
+
+    public CabArchiveCreator(OutputStream os) {
+        this.os = new CabOutputStream(os);
+    }
+
+    @Override
+    public ArchiveEntry newEntry(String name) {
+        return CabEntry.getInstance(name);
+    }
+
+    @Override
+    public void addEntry(ArchiveEntry entry, File file) throws IOException {
+        if (file.isDirectory()) {
+            os.putNextEntry(toCabEntry(entry));
+            os.closeEntry();
+        }
+        else {
+            InputStream is = new FileInputStream(file);
+            try {
+                addEntry(entry, is, file.length());
+            }
+            finally {
+                is.close();
+            }
+        }
+        entry.setAdded(true);
+    }
+
+    @Override
+    public void addEntry(ArchiveEntry entry, InputStream is, long length) throws IOException {
+        CabEntry fileEntry = toCabEntry(entry);
+        fileEntry.setSize(length);
+        os.putNextEntry(fileEntry);
+        final long size = IOUtilities.transferAll(is, os);
+        os.closeEntry();
+        assert size == fileEntry.getSize() : "file size";
+        assert size == length : "file size";
+        entry.setSize(size);
+        entry.setAdded(true);
+    }
+
+    static CabEntry toCabEntry(ArchiveEntry entry) {
+        if (entry instanceof CabEntry)
+            return (CabEntry)entry;
+        CabEntry newEntry = CabEntry.getInstance(entry.getName());
+        entry.copyTo(newEntry);
+        return newEntry;
+    }
+
+    @Override
+    public void close() throws IOException {
+        os.close();
+    }
+
+}