Java压缩文件

压缩文件

  1 package com.iss.cpf.windmanger.userprivilegeexport.bizlogic;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileOutputStream;
  8 import java.io.IOException;
  9 import java.util.Enumeration;
 10 import java.util.zip.CRC32;
 11 import java.util.zip.CheckedOutputStream;
 12 import java.util.zip.ZipFile;
 13 
 14 import org.apache.commons.lang.StringUtils;
 15 import org.apache.tools.zip.ZipEntry;
 16 import org.apache.tools.zip.ZipOutputStream;
 17 
 18 public class ZipBiz {
 19 
 20     
 21     /**
 22      * 递归压缩文件夹
 23      * @param srcRootDir 压缩文件夹根目录的子路径
 24      * @param file 当前递归压缩的文件或目录对象
 25      * @param zos 压缩文件存储对象
 26      * @throws Exception
 27      */
 28     private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception
 29     {
 30         if (file == null) 
 31         {
 32             return;
 33         }                
 34         
 35         //如果是文件,则直接压缩该文件
 36         if (file.isFile())
 37         {            
 38             int count, bufferLen = 1024;
 39             byte data[] = new byte[bufferLen];
 40         
 41             
 42             //获取文件相对于压缩文件夹根目录的子路径
 43             String subPath = file.getAbsolutePath();
 44             int index = subPath.indexOf(srcRootDir);
 45             if (index != -1) 
 46             {
 47                 subPath = subPath.substring(srcRootDir.length() + File.separator.length());
 48             }
 49             ZipEntry entry = new ZipEntry(subPath);
 50             entry.setUnixMode(644);//解决Linux乱码
 51             zos.putNextEntry(entry);
 52             zos.setEncoding("GBK");
 53             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
 54             while ((count = bis.read(data, 0, bufferLen)) != -1) 
 55             {
 56                 zos.write(data, 0, count);
 57             }
 58             bis.close();
 59             zos.closeEntry();
 60         }
 61         //如果是目录,则压缩整个目录
 62         else 
 63         {
 64             //压缩目录中的文件或子目录
 65             File[] childFileList = file.listFiles();
 66             for (int n=0; n<childFileList.length; n++)
 67             {
 68                 childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
 69                 zip(srcRootDir, childFileList[n], zos);
 70             }
 71         }
 72     }
 73     
 74     /**
 75      * 对文件或文件目录进行压缩
 76      * @param srcPath 要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径
 77      * @param zipPath 压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹
 78      * @param zipFileName 压缩文件名
 79      * @throws Exception
 80      */
 81     public static void zip(String srcPath, String zipPath, String zipFileName) throws Exception
 82     {
 83         if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(zipPath) || StringUtils.isEmpty(zipFileName))
 84         {
 85             throw new Exception("路径不正确");
 86         }
 87         CheckedOutputStream cos = null;
 88         ZipOutputStream zos = null;                        
 89         try
 90         {
 91             File srcFile = new File(srcPath);
 92             
 93             //判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)
 94             //若果是本地  路径是从配置文件读取的   /    会导致报错
 95             if (srcFile.isDirectory() && zipPath.indexOf(srcPath)>0) 
 96             {
 97                 throw new Exception("zipPath must not be the child directory of srcPath= "+srcFile);
 98             }
 99             
100             //判断压缩文件保存的路径是否存在,如果不存在,则创建目录
101             File zipDir = new File(zipPath);
102             if (!zipDir.exists() || !zipDir.isDirectory())
103             {
104                 zipDir.mkdirs();
105             }
106             
107             //创建压缩文件保存的文件对象
108             String zipFilePath = zipPath + File.separator + zipFileName;
109             File zipFile = new File(zipFilePath);            
110             if (zipFile.exists())
111             {
112                 //检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
113                 SecurityManager securityManager = new SecurityManager();
114                securityManager.checkDelete(zipFilePath);
115                 //删除已存在的目标文件
116                 zipFile.delete();                
117             }
118             
119             cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());
120             zos = new ZipOutputStream(cos);
121             
122             //如果只是压缩一个文件,则需要截取该文件的父目录
123             String srcRootDir = srcPath;
124             if (srcFile.isFile())
125             {
126                 int index = srcPath.lastIndexOf(File.separator);
127                 if (index != -1)
128                 {
129                     srcRootDir = srcPath.substring(0, index);
130                 }
131             }
132             //调用递归压缩方法进行目录或文件压缩
133             zip(srcRootDir, srcFile, zos);
134             zos.flush();
135         }
136         catch (Exception e) 
137         {
138             throw e;
139         }
140         finally 
141         {            
142             try
143             {
144                 if (zos != null)
145                 {
146                     zos.close();
147                 }                
148             }
149             catch (Exception e)
150             {
151                 e.printStackTrace();
152             }            
153         }
154     }
155     
156     /**
157      * 解压缩zip包
158      * @param zipFilePath zip文件的全路径
159      * @param unzipFilePath 解压后的文件保存的路径
160      * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
161      */
162     @SuppressWarnings("unchecked")
163     public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception
164     {
165         if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(unzipFilePath))
166         {
167             throw new Exception("路径为空");            
168         }
169         File zipFile = new File(zipFilePath);
170         //如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
171         if (includeZipFileName)
172         {
173             String fileName = zipFile.getName();
174             if (StringUtils.isNotEmpty(fileName))
175             {
176                 fileName = fileName.substring(0, fileName.lastIndexOf("."));
177             }
178             unzipFilePath = unzipFilePath + File.separator + fileName;
179         }
180         //创建解压缩文件保存的路径
181         File unzipFileDir = new File(unzipFilePath);
182         if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())
183         {
184             unzipFileDir.mkdirs();
185         }
186         
187         //开始解压
188         ZipEntry entry = null;
189         String entryFilePath = null, entryDirPath = null;
190         File entryFile = null, entryDir = null;
191         int index = 0, count = 0, bufferSize = 1024;
192         byte[] buffer = new byte[bufferSize];
193         BufferedInputStream bis = null;
194         BufferedOutputStream bos = null;
195         ZipFile zip = new ZipFile(zipFile);
196         Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();
197         //循环对压缩包里的每一个文件进行解压        
198         while(entries.hasMoreElements())
199         {
200             entry = entries.nextElement();
201             //构建压缩包中一个文件解压后保存的文件全路径
202             entryFilePath = unzipFilePath + File.separator + entry.getName();
203             //构建解压后保存的文件夹路径
204             index = entryFilePath.lastIndexOf(File.separator);
205             if (index != -1)
206             {
207                 entryDirPath = entryFilePath.substring(0, index);
208             }
209             else
210             {
211                 entryDirPath = "";
212             }            
213             entryDir = new File(entryDirPath);
214             //如果文件夹路径不存在,则创建文件夹
215             if (!entryDir.exists() || !entryDir.isDirectory())
216             {
217                 entryDir.mkdirs();
218             }
219             
220             //创建解压文件
221             entryFile = new File(entryFilePath);
222             if (entryFile.exists())
223             {
224                 //检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
225                 SecurityManager securityManager = new SecurityManager();
226                 securityManager.checkDelete(entryFilePath);
227                 //删除已存在的目标文件
228                 entryFile.delete();    
229             }
230             
231             //写入文件
232             bos = new BufferedOutputStream(new FileOutputStream(entryFile));
233             bis = new BufferedInputStream(zip.getInputStream(entry));
234             while ((count = bis.read(buffer, 0, bufferSize)) != -1)
235             {
236                 bos.write(buffer, 0, count);
237             }
238             bos.flush();
239             bos.close();            
240         }
241     }
242     /**
243      * 复制文件
244      * @param fromFile
245      * @param toFile
246      * <br/>
247      * 2018年4月9日  下午3:31:50
248      * @throws IOException 
249      */
250     public void copyFile(File fromFile,File toFile) throws IOException{
251         //如果目标文件不存在,则创建
252         File parentFile = toFile.getParentFile();
253         if(!parentFile.exists()){
254             parentFile.mkdirs();
255         }
256         if(!toFile.exists()){
257             toFile.createNewFile();
258         }
259         //复制文件
260         FileInputStream ins = new FileInputStream(fromFile);
261         FileOutputStream out = new FileOutputStream(toFile);
262         byte[] b = new byte[1024];
263         int n=0;
264         while((n=ins.read(b))!=-1){
265             out.write(b, 0, n);
266         }
267         
268         ins.close();
269         out.close();
270     }
271  
272     public static void main(String[] args) 
273     {
274         String zipPath = "/appshare/cpfupload/windmanger/userManageExport/17/zip";
275         String dir = "/appshare/cpfupload/windmanger/userManageExport/17";
276 //        String zipFileName = "test.zip";
277 
278         
279         long i=zipPath.indexOf(dir);
280         
281         
282         System.out.print(i);
283         
284         String zipFilePath = "D:\\ziptest\\zipPath\\test.zip";
285         String unzipFilePath = "D:\\ziptest\\zipPath";
286         try 
287         {
288 //            unzip(zipFilePath, unzipFilePath, true);
289         }
290         catch (Exception e)
291         {
292             e.printStackTrace();
293         }
294 
295     }
296 
297 
298 }

 

posted @ 2018-04-12 14:31  溪山晴雪  阅读(171)  评论(0编辑  收藏  举报