java解压多目录Zip文件(解决中文乱码问题)-文件夹乱码

java解压多目录Zip文件(解决中文乱码问题)

Java代码

  1. import java.io.BufferedOutputStream;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.Enumeration;
  7. import org.apache.tools.zip.ZipEntry;
  8. import org.apache.tools.zip.ZipFile;
  9. /**
  10. * 解压Zip文件工具类
  11. * @author zhangyongbo
  12. *
  13. */
  14. public class ZipUtil {
  15. private static final int buffer = 2048;
  16. public static void main(String[] args)
  17. {
  18. unZip("E:\\java\\Android\\aaa.zip");
  19. }
  20. /**
  21. * 解压Zip文件
  22. * @param path 文件目录
  23. */
  24. public static void unZip(String path)
  25. {
  26. int count = -1;
  27. String savepath = "";
  28. File file = null;
  29. InputStream is = null;
  30. FileOutputStream fos = null;
  31. BufferedOutputStream bos = null;
  32. savepath = path.substring(0, path.lastIndexOf(".")) + File.separator; //保存解压文件目录
  33. new File(savepath).mkdir(); //创建保存目录
  34. ZipFile zipFile = null;
  35. try
  36. {
  37. zipFile = new ZipFile(path,"gbk"); //解决中文乱码问题
  38. Enumeration<?> entries = zipFile.getEntries();
  39. while(entries.hasMoreElements())
  40. {
  41. byte buf[] = new byte[buffer];
  42. ZipEntry entry = (ZipEntry)entries.nextElement();
  43. String filename = entry.getName();
  44. boolean ismkdir = false;
  45. if(filename.lastIndexOf("/") != -1){ //检查此文件是否带有文件夹
  46. ismkdir = true;
  47. }
  48. filename = savepath + filename;
  49. if(entry.isDirectory()){ //如果是文件夹先创建
  50. file = new File(filename);
  51. file.mkdirs();
  52. continue;
  53. }
  54. file = new File(filename);
  55. if(!file.exists()){ //如果是目录先创建
  56. if(ismkdir){
  57. new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs(); //目录先创建
  58. }
  59. }
  60. file.createNewFile(); //创建文件
  61. is = zipFile.getInputStream(entry);
  62. fos = new FileOutputStream(file);
  63. bos = new BufferedOutputStream(fos, buffer);
  64. while((count = is.read(buf)) > -1)
  65. {
  66. bos.write(buf, 0, count);
  67. }
  68. bos.flush();
  69. bos.close();
  70. fos.close();
  71. is.close();
  72. }
  73. zipFile.close();
  74. }catch(IOException ioe){
  75. ioe.printStackTrace();
  76. }finally{
  77. try{
  78. if(bos != null){
  79. bos.close();
  80. }
  81. if(fos != null) {
  82. fos.close();
  83. }
  84. if(is != null){
  85. is.close();
  86. }
  87. if(zipFile != null){
  88. zipFile.close();
  89. }
  90. }catch(Exception e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. }
  95. }

推荐阅读