Android で、ZIP圧縮を試す

Android で、java.util.zip.ZipOutputStream 等を使って作成するZIPファイルは、
日本語ファイル名が文字化けしたり、Windows PCに転送して解凍しようとしても、
解凍ツールによっては失敗したりする。

Apache Ant で配布されている org.apache.tools.zip を持ってきて使えば、問題なく解凍できる。

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

  :
  ;
/**
 * ZIP圧縮実行.
 *   キャッシュディレクトリ上、/data/Android/package/cache/ にZIPを生成
 * @param entryName ZIPファイル名=entryName+",zip" , entryName をルートディレクトリとする。
 * @param targets 圧縮対象のファイル List
 * @return ZIPファイル File 
 */

protected File compressZip(String entryName,List<File> targets){
   File cacheDir = getExternalCacheDir();
   File zipFile = new File(cacheDir.getAbsolutePath()+"/"+entryName+".zip");
   try{
      byte[] buf = new byte[1024];
      ZipOutputStream zos = new ZipOutputStream(zipFile);
      zos.setMethod(ZipOutputStream.DEFLATED);

      for(File file : targets){
         ZipEntry entry = new ZipEntry(entryName+"/"+file.getName());
         zos.putNextEntry(entry);
         int len = 0;
         InputStream is = new FileInputStream(file);
         while*1 != -1){
            zos.write(buf,0,len);
            zos.flush();
         }
         zos.closeEntry();
         is.close();
      }
      zos.close();

   }catch(Exception e){
      android.util.Log.e(TAG,e.getMessage(),e);
      throw new RuntimeException(e);
   }
   return zipFile;
}
---------
setEncode とか実行しなくても日本語ファイル名の文字化けはなかった。

実践ではこれを、AsyncTask などで実行すべきであろう。

*1:len=is.read(buf