解压zip文件

来源:互联网 发布:xnview mac 中文版 编辑:程序博客网 时间:2024/06/16 08:22
<pre name="code" class="java">//解压制定目录private static void unZipFolderOfFile(File file, String folder,String destFolderPath) throws Exception {File parent = new File(destFolderPath);if (!parent.exists() && !parent.mkdirs()) {throw new Exception("create dir \"" + parent.getAbsolutePath()+ "\" fail!!");}ZipInputStream zipStream = new ZipInputStream(new FileInputStream(file));ZipEntry zipEntry = zipStream.getNextEntry();while (zipEntry != null) {String fileName = zipEntry.getName();if (!fileName.startsWith(folder + "/")) {zipEntry = zipStream.getNextEntry();continue;}// fileName = fileName.substring((folder + "/").length());fileName = fileName.substring(fileName.lastIndexOf("/") + 1);File tmpFile = new File(parent, fileName);if (zipEntry.isDirectory()) {// if(!tmpFile.exists()) {// tmpFile.mkdirs();// }zipEntry = zipStream.getNextEntry();continue;}if (!tmpFile.exists()) {tmpFile.createNewFile();}FileOutputStream tmpOutputStream = new FileOutputStream(tmpFile);byte[] buffer = new byte[4096];int hasRead = 0;while ((hasRead = zipStream.read(buffer)) > 0) {tmpOutputStream.write(buffer, 0, hasRead);}buffer = null;tmpOutputStream.flush();tmpOutputStream.close();zipEntry = zipStream.getNextEntry();}zipStream.close();}

public static void unZipFile(File file, String folderPath)throws FileNotFoundException, IOException {File srcZipFile = file;if (!folderPath.endsWith("/")) {folderPath += "/";}String prefixion = folderPath;ZipInputStream zipInput = new ZipInputStream(new FileInputStream(srcZipFile));ZipEntry zipEntry = null;while ((zipEntry = zipInput.getNextEntry()) != null) {String fileName = zipEntry.getName();File tmpFile = new File(prefixion + fileName);if (!tmpFile.getParentFile().exists()) {tmpFile.getParentFile().mkdirs();}if (zipEntry.isDirectory()) {if (!tmpFile.exists()) {tmpFile.mkdir();}continue;}if (!tmpFile.exists()) {tmpFile.createNewFile();}FileOutputStream tmpOutputStream = new FileOutputStream(tmpFile);byte[] buffer = new byte[1024];int hasRead = 0;while ((hasRead = zipInput.read(buffer)) > 0) {tmpOutputStream.write(buffer, 0, hasRead);}buffer = null;tmpOutputStream.flush();tmpOutputStream.close();}zipInput.close();}




0 0
原创粉丝点击