1. import java.io.File; 2. import java.io.FileInputStream; 3. import java.io.FileNotFoundException; 4. import java.io.FileOutputStream; 5. import java.io.IOException; 6. import java.io.InputStream; 7. 8. import org.apache.tools.zip.ZipEntry; 9. import org.apache.tools.zip.ZipOutputStream; 10. 11. 12. public class ZipDemo3 13. { 14. public static void main(String [] args) 15. { 16. File dir = new File("F:"+File.separator+"皓皓的生日礼物"); 17. File zip = new File("F:"+File.separator+"皓皓的生日礼物.zip"); 18. ZipOutputStream zo = null; 19. try { 20. zo = new ZipOutputStream(new FileOutputStream(zip)); 21. } catch (FileNotFoundException e) { 22. e.printStackTrace(); 23. } 24. 25. zipFile(dir,zo,""); 26. 27. if(zo!=null) 28. { 29. try { 30. zo.close(); 31. } catch (IOException e) { 32. e.printStackTrace(); 33. } 34. } 35. } 36. 37. private static void zipFile(File dir, ZipOutputStream zo,String base) 38. { 39. 40. 41. try { 42. 43. zo.setEncoding("GBK");//防止中文乱码现象的出现 44. zo.setComment("压缩文件夹Demo"); 45. 46. boolean firstDir = false; 47. if(dir.isDirectory()) 48. { 49. firstDir = true; 50. File [] subFiles = dir.listFiles(); 51. 52. zo.putNextEntry(new ZipEntry(base+"/")); 53. base = base.length() == 0 ? "" : base + "/"; 54. for (File file :subFiles) 55. { 56. zipFile(file,zo,base+file.getName()); 57. } 58. }else 59. { 60. InputStream is = new FileInputStream(dir); 61. System.out.println(base); 62. if( !firstDir ) 63. { 64. zo.putNextEntry(new ZipEntry(dir.getName())); 65. }else 66. zo.putNextEntry(new ZipEntry(base)); 67. 68. int len = 0; 69. byte [] buf = new byte[BUF]; 70. while((len = is.read(buf))!=-1) 71. { 72. zo.write(buf, 0, len); 73. } 74. zo.flush(); 75. 76. if(is!=null) 77. { 78. is.close(); 79. } 80. 81. } 82. 83. 84. 85. } catch (FileNotFoundException e) { 86. e.printStackTrace(); 87. } catch (IOException e) { 88. e.printStackTrace(); 89. } 90. 91. 92. 93. } 94. public static int BUF = 1024*10; 95. 96. }