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 45 46 47 48 49 50 51 52 53 54
| ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
File fileWillZip = new File(dir);
if (fileWillZip.exists()) { if(fileWillZip.isDirectory()){ compressZip(zipOut,fileWillZip,fileWillZip.getName()); } else { zip(zipOut,fileWillZip,dir); } } zipOut.closeEntry(); zipOut.close();
private void compressZip(ZipOutputStream zipOutput, File file, String suffixpath) { File[] listFiles = file.listFiles(); for(File fi : listFiles){ if(fi.isDirectory()){ if(suffixpath.equals("")){ compressZip(zipOutput, fi, fi.getName()); }else{ compressZip(zipOutput, fi, suffixpath + File.separator + fi.getName()); } }else{ zip(zipOutput, fi, suffixpath); } } }
public void zip(ZipOutputStream zipOutput, File file, String suffixpath) { try { ZipEntry zEntry = null; if(suffixpath.equals("")){ zEntry = new ZipEntry(file.getName()); }else{ zEntry = new ZipEntry(suffixpath + File.separator + file.getName()); } zipOutput.putNextEntry(zEntry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int read = 0; while((read = bis.read(buffer)) != -1){ zipOutput.write(buffer, 0, read); } bis.close(); } catch (Exception e) { e.printStackTrace(); } }
|