Java tutorial
//package com.java2s; //License from project: Apache License import java.io.*; import java.util.zip.*; public class Main { /** * Compress a String to a zip file that has only one entry like zipName * The name shouldn't have .zip * * @param content * @param fName * @throws IOException */ public static void zipAContentAsFileName(String fName, String content, String charset) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes(charset)); BufferedInputStream bis = new BufferedInputStream(bais); File f = new File(fName); File parentFile = f.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } ZipOutputStream zf = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f + ".zip"))); ZipEntry entry = new ZipEntry(f.getName()); zf.putNextEntry(entry); byte[] barr = new byte[8192]; int len = 0; while ((len = bis.read(barr)) != -1) { zf.write(barr, 0, len); } zf.flush(); zf.close(); bis.close(); bais.close(); } /** * Compress a String to a zip file that has only one entry like zipName * The name shouldn't have .zip. Charset UTF-8 * * @param content * @param fName * @throws IOException */ public static void zipAContentAsFileName(String content, String fName) throws IOException { zipAContentAsFileName(fName, content, "UTF-8"); } public static void close(Closeable closable) { if (closable != null) { try { closable.close(); } catch (IOException e) { e.printStackTrace(); } } } }