1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
public class zip {
public static void main(String args[]) throws IOException { File inFile = new File("D:\test.txt"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:\test.zip"), Charset.forName("GBK")); zos.setComment("ziped by Ming Cheng."); zipFile(inFile, zos, ""); zos.close(); }
public static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException { if (inFile.isDirectory()) { File[] files = inFile.listFiles(); for (File file:files) zipFile(file, zos, dir + "\" + inFile.getName()); } else { String entryName = null; if (!"".equals(dir)) entryName = dir + "\" + inFile.getName(); else entryName = inFile.getName(); ZipEntry entry = new ZipEntry(entryName); zos.putNextEntry(entry); InputStream is = new FileInputStream(inFile); int len = 0; while ((len = is.read()) != -1) zos.write(len); is.close(); } } }
|
近期评论