java.util.zip.ZipFile

ZipFileの展開をするには、java.util.zip.ZipFileを使用する。アーカイブされているファイル情報として、ディレクトリ情報もきちんと入っている場合と、そうでない場合とがあり、どちらにも対応するのは少々面倒な処理となる。少し泥臭いソースコードになったが、とりあえず、これでOpenOffice Impressのファイルを展開することができるようになった。

興味のある方は、ソースコードをどうぞ。


package org.sssg.four.java.ziputil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Starter {
    private ZipFile zipFile;

    private int BUFFER_SIZE = 8092;

    private byte[] b;

    public Starter() {
        b = new byte[BUFFER_SIZE];
    }

    public void extract(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }
        try {
            zipFile = new ZipFile(file, ZipFile.OPEN_READ);
            Enumeration entris = zipFile.entries();
            while (entris.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entris.nextElement();
                extractFile(entry);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String fs = System.getProperty("file.separator");

    public void extractFile(ZipEntry e) throws IOException {
        if (e.isDirectory()) {
            File dir = new File(e.getName());
            if (!dir.exists()) {
                System.err.println("Make directory 1 " + e.getName());
                dir.mkdir();
            }
            return;
        }
        String fileName = e.getName();
        File entry = new File(e.getName());
        if (!entry.getName().equals(fileName)) {
            int length = fileName.length() – entry.getName().length();
            fileName = fileName.substring(0, length – 1) + fs;
            File dir = new File(fileName);
            if (!dir.exists()) {
                System.err.println("Make directory 2 " + fileName);
                dir.mkdir();
            }
        }
        System.err.println("Extracting file " + entry);
        FileOutputStream os = new FileOutputStream(entry);
        InputStream is = zipFile.getInputStream(e);
        int n = 0;
        while ((n = is.read(b)) > 0) {
            os.write(b, 0, n);
        }
        is.close();
        os.close();
    }

    public static void main(String[] args) {
        Starter u = new Starter();
        String sxi = null;
        if (args.length == 1) {
            sxi = args[0];
        } else {
            System.out
                    .println("Usage: java org.sssg.four.java.ziputil.Starter <file name>");
            return;
        }

        if (sxi.endsWith(".sxi")) {
            u.extract(sxi);
        } else {
            System.err.println(sxi + " はOpenOffice Impress ファイルではありません。");
        }
    }
}

同じカテゴリの記事: Java