在工作過程中,需要將一個文件夾生成壓縮文件,然后提供給用戶下載。所以自己寫了一個壓縮文件的工具類。該工具類支持單個文件和文件夾壓縮。放代碼:
1 import java.io.BufferedOutputStream; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 6 import org.apache.tools.zip.ZipEntry; 7 import org.apache.tools.zip.ZipOutputStream; 8 9 /** 10 * @project: Test 11 * @author chenssy 12 * @date 2013-7-28 13 * @Description: 文件壓縮工具類 14 * 將指定文件/文件夾壓縮成zip、rar壓縮文件 15 */ 16 public class CompressedFileUtil { 17 /** 18 * 默認構造函數 19 */ 20 public CompressedFileUtil(){ 21 22 } 23 24 /** 25 * @desc 將源文件/文件夾生成指定格式的壓縮文件,格式zip 26 * @param resourePath 源文件/文件夾 27 * @param targetPath 目的壓縮文件保存路徑 28 * @return void 29 * @throws Exception 30 */ 31 public void compressedFile(String resourcesPath,String targetPath) throws Exception{ 32 File resourcesFile = new File(resourcesPath); //源文件 33 File targetFile = new File(targetPath); //目的 34 //如果目的路徑不存在,則新建 35 if(!targetFile.exists()){ 36 targetFile.mkdirs(); 37 } 38 39 String targetName = resourcesFile.getName()+".zip"; //目的壓縮文件名 40 FileOutputStream outputStream = new FileOutputStream(targetPath+"\\"+targetName); 41 ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream)); 42 43 createCompressedFile(out, resourcesFile, ""); 44 45 out.close(); 46 } 47 48 /** 49 * @desc 生成壓縮文件。 50 * 如果是文件夾,則使用遞歸,進行文件遍歷、壓縮 51 * 如果是文件,直接壓縮 52 * @param out 輸出流 53 * @param file 目標文件 54 * @return void 55 * @throws Exception 56 */ 57 public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{ 58 //如果當前的是文件夾,則進行進一步處理 59 if(file.isDirectory()){ 60 //得到文件列表信息 61 File[] files = file.listFiles(); 62 //將文件夾添加到下一級打包目錄 63 out.putNextEntry(new ZipEntry(dir+"/")); 64 65 dir = dir.length() == 0 ? "" : dir +"/"; 66 67 //循環將文件夾中的文件打包 68 for(int i = 0 ; i < files.length ; i++){ 69 createCompressedFile(out, files[i], dir + files[i].getName()); //遞歸處理 70 } 71 } 72 else{ //當前的是文件,打包處理 73 //文件輸入流 74 FileInputStream fis = new FileInputStream(file); 75 76 out.putNextEntry(new ZipEntry(dir)); 77 //進行寫操作 78 int j = 0; 79 byte[] buffer = new byte[1024]; 80 while((j = fis.read(buffer)) > 0){ 81 out.write(buffer,0,j); 82 } 83 //關閉輸入流 84 fis.close(); 85 } 86 } 87 88 public static void main(String[] args){ 89 CompressedFileUtil compressedFileUtil = new CompressedFileUtil(); 90 91 try { 92 compressedFileUtil.compressedFile("G:\\zip", "F:\\zip"); 93 System.out.println("壓縮文件已經生成..."); 94 } catch (Exception e) { 95 System.out.println("壓縮文件生成失敗..."); 96 e.printStackTrace(); 97 } 98 } 99 }
運行程序結果如下:
壓縮之前的文件目錄結構:
提示:如果是使用java.util下的java.util.zip進行打包處理,可能會出現中文亂碼問題,這是因為java的zip方法不支持編碼格式的更改,我們可以使用ant.java下的zip工具類來進行打包處理。所以需要將ant.jar導入項目的lib目錄下。