blitz-time アプリ開発ブログ

Androidアプリ開発などのTips集

【Androidアプリ開発】ファイルをまとめてZip化(圧縮・解凍)

ファイルをバックアップ・復元するために、複数のファイルを圧縮・解凍する機能が必要です。
便利なオープンソースがあるので、そちらを活用します。

github.com

簡単な使い方はこのような感じです。

public class ZipUtils {

    Context mContext;

    public ZipUtils( Context ctx ) {
        mContext = ctx;
    }

    /**
     * ファイルとフォルダを圧縮する
     * @param 圧縮するFile
     * @param zipName 生成されるzipファイルのパス
     * */
    public void compressFiles( final String szLocation,
            final File[] files, final String zipFilePath )
    {
        File zipFile = new File(zipFilePath);
        String strTempFile = zipFile.getParent() + "/temp.zip";

        try{
            ZipEntrySource[] entries = new ZipEntrySource[files.length];
            int cnt = 0;
            for( File file : files ){
                entries[cnt] = new FileSource( szLocation + file.getName(), file );
                cnt++;
            }
            if( zipFile.exists() ){
                File tempFile = new File(strTempFile);
                ZipUtil.addEntries(zipFile, entries, tempFile );       //  Zipファイルが存在しないとエラーになる
                //  元のファイルを削除
                zipFile.delete();
                //  strTempFileをリネーム
                tempFile.renameTo( zipFile );
            }else {
                ZipUtil.pack( entries, zipFile);
            }
        }catch(ZipException e) {
            e.printStackTrace();
        }
    }

    //--------------------------------------------------------
    //  zipFilePath: 解凍するファイル
    //--------------------------------------------------------
    public void decompressFile( String zipFilePath, final String strMapper, String outputDir ){

        ZipUtil.unpack(new File(zipFilePath), new File(outputDir), new NameMapper() {
            public String map(String name) {
                if( name.startsWith(strMapper) ){
                    String strFile = name.substring(strMapper.length(),name.length());
                    return strFile;
                }else return null;
            }
        });
    }
}

Gradleのほうには、下記の記述の追加が必要です。

dependencies {
    implementation 'org.zeroturnaround:zt-zip:1.12'
}