2012-05-17 49 views
16

Có mã mẫu nào không, làm thế nào để particaly giải nén thư mục từ ZIP vào thư mục mong muốn của tôi? Tôi đã đọc tất cả các tệp từ thư mục "FOLDER" thành mảng byte, làm cách nào để tạo lại từ cấu trúc tệp của nó?Java ZIP - cách giải nén thư mục?

Trả lời

0

Bạn sẽ nhận được tất cả các mục từ tập tin zip của bạn:

Enumeration entries = zipFile.getEntries(); 

sau đó itareting trên liệt kê này có được ZipEntry từ nó, kiểm tra xem nó là một thư mục hay không, và tạo dirctrory hoặc chỉ trích xuất một respectivly tập tin .

+0

Đây là phần tôi thực sự cần ... Tôi có quyền truy cập vào thư mục của tôi ZIP và muốn lưu trữ nó trong sdcard/tên người dùng với nội dung của nó từ ZIP. Làm thế nào để làm điều đó? – Waypoint

+1

tốt, tôi nghĩ bạn nên cố gắng viết một số mã, xem xét một số ví dụ và nếu bạn thất bại hoặc gặp khó khăn - hãy quay lại đây với mã của bạn. –

21

Đây là mã tôi đang sử dụng. Thay đổi BUFFER_SIZE cho nhu cầu của bạn.

import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 

public class ZipUtils 
{ 
    private static final int BUFFER_SIZE = 4096; 

    private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException 
    { 
    byte[] buffer = new byte[BUFFER_SIZE]; 
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name))); 
    int count = -1; 
    while ((count = in.read(buffer)) != -1) 
     out.write(buffer, 0, count); 
    out.close(); 
    } 

    private static void mkdirs(File outdir,String path) 
    { 
    File d = new File(outdir, path); 
    if(!d.exists()) 
     d.mkdirs(); 
    } 

    private static String dirpart(String name) 
    { 
    int s = name.lastIndexOf(File.separatorChar); 
    return s == -1 ? null : name.substring(0, s); 
    } 

    /*** 
    * Extract zipfile to outdir with complete directory structure 
    * @param zipfile Input .zip file 
    * @param outdir Output directory 
    */ 
    public static void extract(File zipfile, File outdir) 
    { 
    try 
    { 
     ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile)); 
     ZipEntry entry; 
     String name, dir; 
     while ((entry = zin.getNextEntry()) != null) 
     { 
     name = entry.getName(); 
     if(entry.isDirectory()) 
     { 
      mkdirs(outdir,name); 
      continue; 
     } 
     /* this part is necessary because file entry can come before 
     * directory entry where is file located 
     * i.e.: 
     * /foo/foo.txt 
     * /foo/ 
     */ 
     dir = dirpart(name); 
     if(dir != null) 
      mkdirs(outdir,dir); 

     extractFile(zin, outdir, name); 
     } 
     zin.close(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 
+4

Bạn không nên nuốt IOException. –

+0

Nó hoạt động cho tôi. Cảm ơn. –

10

Cùng có thể đạt được bằng thư viện Ant Compress. Nó sẽ bảo vệ cấu trúc thư mục.

Maven phụ thuộc: -

<dependency> 
    <groupId>org.apache.ant</groupId> 
    <artifactId>ant-compress</artifactId> 
    <version>1.2</version> 
</dependency> 

Mẫu mã: -

Unzip unzipper = new Unzip(); 
unzipper.setSrc(theZIPFile); 
unzipper.setDest(theTargetFolder); 
unzipper.execute(); 
24

Tôi không chắc chắn những gì bạn có nghĩa là bởi particaly? Bạn có tự làm điều đó mà không cần trợ giúp API không?

Trong trường hợp bạn không nhớ sử dụng một số thư viện mã nguồn mở, có một API mát cho rằng ngoài kia gọi zip4J

Nó rất dễ dàng để sử dụng và tôi nghĩ rằng đó là phản hồi tốt về nó. Xem ví dụ này:

String source = "folder/source.zip"; 
String destination = "folder/source/"; 

try { 
    ZipFile zipFile = new ZipFile(source); 
    zipFile.extractAll(destination); 
} catch (ZipException e) { 
    e.printStackTrace(); 
} 

Nếu các tập tin bạn muốn giải nén có mật khẩu, bạn có thể thử này:

String source = "folder/source.zip"; 
String destination = "folder/source/"; 
String password = "password"; 

try { 
    ZipFile zipFile = new ZipFile(source); 
    if (zipFile.isEncrypted()) { 
     zipFile.setPassword(password); 
    } 
    zipFile.extractAll(destination); 
} catch (ZipException e) { 
    e.printStackTrace(); 
} 

Tôi hy vọng điều này là hữu ích.

2

Đây là giải pháp dễ dàng tuân theo các quy ước hiện đại hơn. Bạn có thể muốn thay đổi kích thước bộ đệm nhỏ hơn nếu bạn đang giải nén các tệp lớn hơn. Điều này là để bạn không giữ tất cả các thông tin tệp trong bộ nhớ.

public static void unzip(File source, String out) throws IOException { 
    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(source))) { 

     ZipEntry entry = zis.getNextEntry(); 

     while (entry != null) { 

      File file = new File(out, entry.getName()); 

      if (entry.isDirectory()) { 
       file.mkdirs(); 
      } else { 
       File parent = file.getParentFile(); 

       if (!parent.exists()) { 
        parent.mkdirs(); 
       } 

       try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { 

        byte[] buffer = new byte[Math.toIntExact(entry.getSize())]; 

        int location; 

        while ((location = zis.read(buffer)) != -1) { 
         bos.write(buffer, 0, location); 
        } 
       } 
      } 
      entry = zis.getNextEntry(); 
     } 
    } 
} 
0

Sau đây là nhiều hơn "hiện đại" hoàn thành mã dựa trên this bài nhưng refactored (và sử dụng Lombok):

import lombok.experimental.var; 
import lombok.val; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.zip.ZipInputStream; 

import static java.nio.file.Files.createDirectories; 

public class UnZip 
{ 
    public static void unZip(String sourceZipFile, String outputDirectory) throws IOException 
    { 
     val folder = new File(outputDirectory); 
     createDirectories(folder.toPath()); 

     try (val zipInputStream = new ZipInputStream(new FileInputStream(sourceZipFile))) 
     { 
      var nextEntry = zipInputStream.getNextEntry(); 

      while (nextEntry != null) 
      { 
       val fileName = nextEntry.getName(); 
       val newFile = new File(outputDirectory + File.separator + fileName); 

       createDirectories(newFile.getParentFile().toPath()); 
       writeFile(zipInputStream, newFile); 

       nextEntry = zipInputStream.getNextEntry(); 
      } 

      zipInputStream.closeEntry(); 
     } 
    } 

    private static void writeFile(ZipInputStream inputStream, File file) throws IOException 
    { 
     val buffer = new byte[1024]; 
     try (val fileOutputStream = new FileOutputStream(file)) 
     { 
      int length; 
      while ((length = inputStream.read(buffer)) > 0) 
      { 
       fileOutputStream.write(buffer, 0, length); 
      } 
     } 
    } 
} 
Các vấn đề liên quan