java - zip

in java •  7 years ago 

public static boolean zip(String znm, StrList flst) {
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
try {
fos = new FileOutputStream(znm);
zipOut = new ZipOutputStream(fos);
for (String fnm : flst) {
File f1 = new File(fnm);
if (!zip1add(f1, f1.getName(), zipOut))
return false;
}
return true;
} catch (IOException ex) {
ex.printStackTrace();
return false;
} finally {
closeQuietly(zipOut);
closeQuietly(fos);
}
}

private static boolean zip1add(File f1, String fnm, ZipOutputStream zipOut) {
    System.out.println("zip1add:" + fnm);
    if (f1.isDirectory()) {
        File[] dlst = f1.listFiles();
        for (File f2 : dlst) {
            zip1add(f2, fnm + "/" + f2.getName(), zipOut);
        }
        return true;
    } else {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f1);
            ZipEntry zipEntry = new ZipEntry(fnm);
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024 * 8];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        } finally {
            closeQuietly(fis);
        }
    }
}
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!