標籤:zip java
最近項目中使用Java實現zip/unzip XML檔案的功能,Java內建的API可以方便實現檔案的壓縮和解壓縮,記錄一下相關代碼。
- 以源檔案名稱zip壓縮源檔案到目標檔案
public void zip(File src, File dest){ InputStream in = null; ZipOutputStream zos= null; try { zos = new ZipOutputStream(new FileOutputStream(dest)); ZipEntry ze= new ZipEntry(src.getName()); zos.putNextEntry(ze); in = new FileInputStream(src); IOUtils.copy(in,zos); } catch (IOException e) { LOG.error("fail to zip file: " + src.getName() + " to : " + dest.getName()); throw e; } finally { if(null != zos){ try { zos.closeEntry(); } catch (IOException ex){ } } IOUtils.closeQuietly(in); IOUtils.closeQuietly(zos);}
- 從源檔案zip解壓所有檔案到目標檔案夾
public void unZip(File file, String outputFolder){ File folder = new File(outputFolder); if(folder.exists() && folder.isFile()){ throw IllegalArgumentException("Not an exists folder"); } //create output directory is not exists if(!folder.exists() && !folder.mkdir()){ throw IllegalStatusException("fail to create dest folder"); } InputStream in = null; OutputStream out = null; ZipFile zipFile = new ZipFile(file); Enumeration emu = zipFile.entries(); while(emu.hasMoreElements()){ ZipEntry entry = (ZipEntry)emu.nextElement(); //建立目錄 if (entry.isDirectory()){ new File(outputFolder + entry.getName()).mkdirs(); continue; } //檔案拷貝 InputStream is = zipFile.getInputStream(entry); File file = new File(outputFolder + entry.getName()); //注意:zipfile讀取檔案是隨機讀取的,可能先讀取一個檔案,再讀取檔案夾,所以可能要先建立目錄 File parent = file.getParentFile(); if(parent != null && (!parent.exists())){ parent.mkdirs(); } out = new FileOutputStream(file); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }catch(IOException ex){ LOG.error(ex.getMessage()); throw ex; } finally { if(null != zipFile){ try{ zipFile.close(); } catch (IOException e) { } } IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
這代碼最主要就是檔案太大的話,IOUtils的copy耗CPU比較高。
Java Zip/Unzip Files 記錄