1. 程式人生 > 實用技巧 >java 解壓檔案

java 解壓檔案

package ofd;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Ofd {

    
public static void main(String[] args) { // 檔案存放位置zip rar尚未測試 String zipPath = "C:\\Users\\Gean_2016\\Desktop\\ofd\\3.ofd"; File zipFile = new File(zipPath); String descDir = "C:\\Users\\Gean_2016\\Desktop\\ofd123\\3\\"; boolean flag = unZip(zipFile, descDir); System.out.println(
"解壓成功還是失敗=" + flag); } /** * 解壓zip檔案 * * @param zipFile目標檔案 * @param descDir解壓後存放的位置 * @return true/false */ public static boolean unZip(File zipFile, String descDir) { boolean flag = false; File pathFile = new File(descDir); if (!pathFile.exists()) { pathFile.mkdirs(); } ZipFile zip
= null; try { // 指定編碼,否則壓縮包裡面不能有中文目錄 zip = new ZipFile(zipFile, Charset.forName("gbk")); for (Enumeration entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zip.getInputStream(entry); String outPath = (descDir + zipEntryName).replace("/",File.separator); // 判斷路徑是否存在,不存在則建立檔案路徑 File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator))); if (!file.exists()) { file.mkdirs(); } // 判斷檔案全路徑是否為資料夾,如果是上面已經上傳,不需要解壓 if (new File(outPath).isDirectory()) { continue; } OutputStream out = new FileOutputStream(outPath); byte[] buf1 = new byte[2048]; int len; while ((len = in.read(buf1)) > 0) { out.write(buf1, 0, len); } in.close(); out.close(); } flag = true; // 必須關閉,否則無法刪除該zip檔案 zip.close(); } catch (IOException e) { e.printStackTrace(); } return flag; } }