/** * 壓縮文件成Gzip格式,Linux上可以使用 * 壓縮文件夾生成後綴名爲".gz"的文件並下載 * @param folderPath,要壓縮的文件夾的路徑 * @param zipFilePath,壓縮後文件的路徑 * @param zipFileName,壓縮後文件的名稱 * @throws BizException * */ public static void CompressedFiles_Gzip(String folderPath, String targzipFilePath, String targzipFileName) { File srcPath =new File(folderPath); int length=srcPath.listFiles().length; byte[] buf = new byte[1024]; //設定讀入緩衝區尺寸 File[] files = srcPath.listFiles(); try { //創建壓縮文件輸出流 FileOutputStream fout=new FileOutputStream(targzipFilePath); //創建tar壓縮輸出流 TarArchiveOutputStream tout=new TarArchiveOutputStream(fout); for(int i=0;i<length;i++) { String filename=srcPath.getPath()+File.separator+files[i].getName(); //打開需壓縮文件做爲文件輸入流 FileInputStream fin=new FileInputStream(filename); //filename是文件全路徑 TarArchiveEntry tarEn=new TarArchiveEntry(files[i]); //此處必須使用new TarEntry(File file); tarEn.setName(files[i].getName()); //此處需重置名稱,默認是帶全路徑的,不然打包後會帶全路徑 tout.putArchiveEntry(tarEn); int num; while ((num=fin.read(buf, 0, 1024)) != -1) { tout.write(buf,0,num); } tout.closeArchiveEntry(); fin.close(); } tout.close(); fout.close(); //創建壓縮文件輸出流 FileOutputStream gzFile=new FileOutputStream(targzipFilePath+".gz"); //創建gzip壓縮輸出流 GZIPOutputStream gzout=new GZIPOutputStream(gzFile); //打開需壓縮文件做爲文件輸入流 FileInputStream tarin=new FileInputStream(targzipFilePath); //targzipFilePath是文件全路徑 int len; while ((len=tarin.read(buf, 0, 1024)) != -1) { gzout.write(buf,0,len); } gzout.close(); gzFile.close(); tarin.close(); File f = new File(targzipFilePath); f.deleteOnExit(); }catch(FileNotFoundException e) { System.out.println(e); }catch(IOException e) { System.out.println(e); } }