Java Zip/Unzip Files 记录

最近项目中使用Java实现zip/unzip XML文件的功能,Java自带的API可以方便实现文件的压缩和解压缩,记录一下相关代码。

以源文件名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解压所有文件到目标文件夹 (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 existsif(!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 记录

相关文章:

你感兴趣的文章:

标签云: