最近進行zip操作,從網上找到一個處理方法,但是經過試驗存在一些bug,主要是文件流的申明存在問題,導致jvm一直占用文件而不釋放,特意把自己修改的發出來,已備記錄
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Zippic { public final static class FileToZip { private FileToZip() { } /** * 將存放在sourceFilePath目錄下的源文件,打包成fileName名稱的ZIP文件,並存放到zipFilePath。 * @param sourceFilePath 待壓縮的文件路徑 * @param zipFilePath 壓縮后存放路徑 * @param fileName 壓縮后文件的名稱 * @return flag */ public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName) { boolean flag = false; File sourceFile = new File(sourceFilePath); if(sourceFile.exists() == false) { System.out.println(">>>>>> 待壓縮的文件目錄:" + sourceFilePath + " 不存在. <<<<<<"); flag = false; return flag; } else { try { File zipFile = new File(zipFilePath + "/" + fileName + ".zip"); if(zipFile.exists()) { System.out.println(">>>>>> " + zipFilePath + " 目錄下存在名字為:" + fileName + ".zip" + " 打包文件. <<<<<<"); } else { File[] sourceFiles = sourceFile.listFiles(); if(null == sourceFiles || sourceFiles.length < 1) { System.out.println(">>>>>> 待壓縮的文件目錄:" + sourceFilePath + " 里面不存在文件,無需壓縮. <<<<<<"); flag = false; return flag; } else { ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
//用到時才申明,否則容易出現問題,記得先開后關,后開先關 byte[] bufs = new byte[1024*10]; //緩沖塊 for(int i=0;i<sourceFiles.length;i++) { // 創建ZIP實體,並添加進壓縮包 ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName()); zos.putNextEntry(zipEntry); // 讀取待壓縮的文件並寫進壓縮包里 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFiles[i]),1024*10);
//用到時才申明,否則容易出現問題,記得先開后關,后開先關 int read = 0; while((read=(bis.read(bufs, 0, 1024*10))) != -1) { zos.write(bufs, 0, read); } if(null != bis) bis.close(); //關閉 } flag = true; if(null != zos) zos.close(); //關閉 } } } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } return flag; } } }