1 import java.io.BufferedInputStream;
  2 import java.io.BufferedOutputStream;
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.InputStream;
  8 import java.io.InputStreamReader;
  9 import java.io.OutputStream;
 10 import java.util.Enumeration;
 11 
 12 import org.slf4j.Logger;
 13 import org.slf4j.LoggerFactory;
 14 /**
 15  * <p>zip 工具类-压缩与解压</p> 
 16  *
 17  * <p>注意:此类中用到的压缩类ZipEntry等都来自于org.apache.tools包而非java.util包</p>
 18  * <p>依赖:ant-1.7.1.jar</p> 
 19  */
 20 public final class ZipUtil {
 21 
 22     private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);
 23 
 24     /** 
 25      * 使用GBK编码可以避免压缩中文文件名乱码 
 26      */  
 27     private static final String CHINESE_CHARSET = "GBK";  
 28 
 29     /** 
 30      * 文件读取缓冲区大小 
 31      */  
 32     private static final int CACHE_SIZE = 1024;
 33 
 34     private ZipUtil() {
 35         
 36     }
 37 
 38     /**
 39        * 
 40        * @Title  zip  
 41        * @Description  压缩文件
 42        * @param  sourceFolder String
 43        * @param  zipFilePath String
 44        * @return
 45        * @throws Exception 异常
 46        */
 47     public static void zip(String sourceFolder, String zipFilePath) throws Exception {  
 48         logger.debug("开始压缩 [" + sourceFolder + "] 到 [" + zipFilePath + "]");
 49         OutputStream out = new FileOutputStream(zipFilePath);  
 50         BufferedOutputStream bos = new BufferedOutputStream(out);  
 51         org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);  
 52         /** 解决中文文件名乱码  */
 53         zos.setEncoding(CHINESE_CHARSET);  
 54         File file = new File(sourceFolder);  
 55         String basePath = null;  
 56         if (file.isDirectory()) {  
 57             basePath = file.getPath();  
 58         } else {  
 59             basePath = file.getParent();  
 60         }  
 61         zipFile(file, basePath, zos);  
 62         zos.closeEntry();  
 63         zos.close();  
 64         bos.close();  
 65         out.close();  
 66         logger.debug("压缩 [" + sourceFolder + "] 完成!");
 67     }
 68 
 69     /**
 70        * 
 71        * @Title  zip  
 72        * @Description  压缩文件
 73        * @param  sourceFolders String[]
 74        * @param  zipFilePath String
 75        * @return
 76        * @throws Exception 异常
 77        */
 78     public static void zip(String[] sourceFolders, String zipFilePath) throws Exception {  
 79         OutputStream out = new FileOutputStream(zipFilePath);  
 80         BufferedOutputStream bos = new BufferedOutputStream(out);  
 81         org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);  
 82         /** 解决中文文件名乱码 */ 
 83         zos.setEncoding(CHINESE_CHARSET);  
 84 
 85         for (int i = 0; i < sourceFolders.length; i++) {
 86             logger.debug("开始压缩 [" + sourceFolders[i] + "] 到 [" + zipFilePath + "]");
 87             File file = new File(sourceFolders[i]);  
 88             String basePath = null;  
 89             basePath = file.getParent();  
 90             zipFile(file, basePath, zos);  
 91         }
 92 
 93         zos.closeEntry();  
 94         zos.close();  
 95         bos.close();  
 96         out.close();  
 97     }
 98 
 99     /**
100     * 
101     * @Title  zipFile  
102     * @Description  压缩文件
103     * @param  parentFile File
104     * @param  basePath String
105     * @param  zos ZipOutputStream
106     * @return
107     * @throws Exception 异常
108     */
109     private static void zipFile(File parentFile,
110             String basePath, org.apache.tools.zip.ZipOutputStream zos) throws Exception {  
111         String basePath1 = basePath;
112         File[] files = new File[0];  
113         if (parentFile.isDirectory()) {  
114             files = parentFile.listFiles();  
115         } else {  
116             files = new File[1];  
117             files[0] = parentFile;  
118         }  
119         String pathName;  
120         InputStream is;  
121         BufferedInputStream bis;  
122         byte[] cache = new byte[CACHE_SIZE];  
123         for (File file : files) {  
124             if (file.isDirectory()) {  
125                 logger.debug("目录:" + file.getPath());
126 
127                 basePath1 = basePath1.replace('\\', '/');
128                 if (basePath1.substring(basePath1.length() - 1).equals("/")) {
129                     pathName = file.getPath().substring(basePath1.length()) + "/";  
130                 } else {
131                     pathName = file.getPath().substring(basePath1.length() + 1) + "/";  
132                 }
133 
134                 zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));  
135                 zipFile(file, basePath1, zos);  
136             } else {  
137                 pathName = file.getPath().substring(basePath1.length());  
138                 pathName = pathName.replace('\\', '/');
139                 if (pathName.substring(0, 1).equals("/")) {
140                     pathName = pathName.substring(1);
141                 }
142 
143                 logger.debug("压缩:" + pathName);
144 
145                 is = new FileInputStream(file);  
146                 bis = new BufferedInputStream(is);  
147                 zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));  
148                 int nRead = 0;  
149                 while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {  
150                     zos.write(cache, 0, nRead);  
151                 }  
152                 bis.close();  
153                 is.close();  
154             }  
155         }  
156     }  
157     
158     /**
159     * 
160     * @Title  unZip  
161     * @Description  解压
162     * @param  zipFileName String
163     * @param  outputDirectory String
164     * @return
165     * @throws Exception 异常
166     */
167     public static void unZip(String zipFileName, String outputDirectory)
168             throws Exception {
169         logger.debug("开始解压 [" + zipFileName + "] 到 [" + outputDirectory + "]");
170         org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);
171 
172         try {
173 
174             Enumeration<?> e = zipFile.getEntries();
175 
176             org.apache.tools.zip.ZipEntry zipEntry = null;
177 
178             createDirectory(outputDirectory, "");
179 
180             while (e.hasMoreElements()) {
181 
182                 zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
183 
184                 logger.debug("解压:" + zipEntry.getName());
185 
186                 if (zipEntry.isDirectory()) {
187 
188                     String name = zipEntry.getName();
189 
190                     name = name.substring(0, name.length() - 1);
191 
192                     File f = new File(outputDirectory + File.separator + name);
193 
194                     f.mkdir();
195 
196                     logger.debug("创建目录:" + outputDirectory + File.separator + name);
197 
198                 } else {
199 
200                     String fileName = zipEntry.getName();
201 
202                     fileName = fileName.replace('\\', '/');
203 
204                     if (fileName.indexOf('/') != -1) {
205 
206                         createDirectory(outputDirectory, fileName.substring(0,
207                                 fileName.lastIndexOf('/')));
208 
209                         fileName = fileName.substring(
210                                 fileName.lastIndexOf('/') + 1,
211                                 fileName.length());
212 
213                     }
214 
215                     File f = new File(outputDirectory + File.separator
216                             + zipEntry.getName());
217 
218                     f.createNewFile();
219 
220                     InputStream in = zipFile.getInputStream(zipEntry);
221 
222                     FileOutputStream out = new FileOutputStream(f);
223 
224                     byte[] by = new byte[1024];
225 
226                     int c;
227 
228                     while ((c = in.read(by)) != -1) {
229 
230                         out.write(by, 0, c);
231 
232                     }
233 
234                     in.close();
235 
236                     out.close();
237 
238                 }
239 
240             }
241             logger.debug("解压 [" + zipFileName + "] 完成!");
242 
243         } catch (Exception ex) {
244 
245             logger.info(ex.getMessage());
246 
247         } finally {
248             zipFile.close();
249         }
250 
251     }
252     
253     /**
254     * 
255     * @Title  createDirectory  
256     * @Description  创建文件夹
257     * @param  directory String
258     * @param  subDirectory String
259     * @return
260     */
261     private static void createDirectory(String directory, String subDirectory) {
262 
263         String directory1 = directory;
264         String dir[];
265 
266         File fl = new File(directory1);
267 
268         try {
269 
270             if (subDirectory.equals("") && !fl.exists()) {
271 
272                 fl.mkdir();
273 
274             } else if (!subDirectory.equals("")) {
275 
276                 dir = subDirectory.replace('\\', '/').split("/");
277 
278                 for (int i = 0; i < dir.length; i++) {
279 
280                     File subFile = new File(directory1 + File.separator + dir[i]);
281 
282                     if (!subFile.exists()) {
283                         subFile.mkdir();
284                     }
285                         
286                     directory1 += File.separator + dir[i];
287 
288                 }
289 
290             }
291 
292         } catch (Exception ex) {
293             logger.info(ex.getMessage());
294         }
295 
296     }  
297 
298     /**
299     * 
300     * @Title  readZipFile  
301     * @Description  无需解压直接读取Zip文件和文件内容
302     * @param  file String
303     * @return
304     * @throws Exception 异常
305     */
306     public static void readZipFile(String file) throws Exception {
307         java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
308         InputStream in = new BufferedInputStream(new FileInputStream(file));
309         java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(in);
310         java.util.zip.ZipEntry ze;
311         while ((ze = zin.getNextEntry()) != null) {
312             if (!ze.isDirectory()) {
313                 logger.info("file - " + ze.getName() + " : "
314                         + ze.getSize() + " bytes");
315                 long size = ze.getSize();
316                 if (size > 0) {
317                     BufferedReader br = new BufferedReader(
318                             new InputStreamReader(zipFile.getInputStream(ze)));
319                     String line;
320                     while ((line = br.readLine()) != null) {
321                         System.out.println(line);
322                     }
323                     br.close();
324                 }
325    
326             }
327         }
328         zin.closeEntry();
329     }
330 
331 /**
332     public static void main(String[] args) throws Exception {
333         try {
334 //          readZipFile("D:\\new1\\文字.zip");
335 
336             //压缩文件
337 //          String sourceFolder = "D:/新建文本文档.txt";  
338 //          String zipFilePath = "D:/新建文本文档.zip";  
339 //          ZipUtil.zip(sourceFolder, zipFilePath);  
340 
341             //压缩文件夹
342 //          String sourceFolder = "D:/fsc1";  
343 //          String zipFilePath = "D:/fsc1.zip";  
344 //          ZipUtil.zip(sourceFolder, zipFilePath);  
345 
346             //压缩一组文件
347 //          String [] paths = {"D:/新建文本文档.txt","D:\\FastStoneCapturecn.zip","D:/new1"};
348 //          zip(paths, "D:/abc.zip");
349 String path= "D://aaaaa.zip";
350           unZip(path, "D:/SSA");  
351         } catch (Exception e) {
352             e.printStackTrace();
353         }
354     }*/
355 
356 }