import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * ZipCompressor */ public class ZipCompressor{ /** ディレクトリ keep */ private boolean dirkeep; /** 圧縮レベル */ private int level = 6; public ZipCompressor(){ dirkeep = true; } public ZipCompressor(boolean dirkeep){ this.dirkeep = dirkeep; } public void setLevel(int level) { this.level = level; } public void create(OutputStream outst, String...paths) throws IOException{ try(ZipOutputStream zout = new ZipOutputStream(outst)){ zout.setLevel(level); Arrays.stream(paths).map(s->new File(s)).forEach(e->{ try{ compress(zout, e); }catch(Exception x){ throw new RuntimeException(x); } }); } } private void compress(ZipOutputStream out, File file) throws IOException { if (file.isDirectory()) { if (dirkeep){ out.putNextEntry(new ZipEntry(file.getPath() + "/")); } for(File f: file.listFiles()){ compress(out, f); } }else{ out.putNextEntry(new ZipEntry(dirkeep ? file.getPath() : file.getName())); byte[] buf = new byte[1024]; int len; try(BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { while((len = in.read(buf, 0, buf.length)) != -1){ out.write(buf, 0, len); } out.flush(); } out.closeEntry(); } } }
コンストラクタで、false を指定することで、ディレクトリを持たせないようにしてます。
この時、対象ファイル名が重複すると、
java.util.zip.ZipException: duplicate entry
が、発生します。