2011-09-04 33 views
5

Tôi tìm thấy ví dụ từ trang web SUN (http://java.sun.com/developer/technicalArticles/Programming/compression/), nhưng nó trả về BufferedOutputStream. Nhưng tôi muốn nhận tệp ZipEntry làm InputStream và sau đó xử lý tệp tiếp theo. Điều đó có thể không? Chương trình của tôi không có quyền truy cập vào đĩa cứng, vì vậy nó thậm chí không thể lưu tạm thời các tệp.Làm cách nào để đọc tệp từ tệp Zip tới bộ nhớ bằng Java?

import java.io.*; 
import java.util.zip.*; 

public class UnZip { 
    final int BUFFER = 2048; 
    public static void main (String argv[]) { 
     try { 
     BufferedOutputStream dest = null; 
     FileInputStream fis = new 
     FileInputStream(argv[0]); 
     ZipInputStream zis = new 
     ZipInputStream(new BufferedInputStream(fis)); 
     ZipEntry entry; 
     while((entry = zis.getNextEntry()) != null) { 
      System.out.println("Extracting: " +entry); 
      int count; 
      byte data[] = new byte[BUFFER]; 
      // write the files to the disk 
      FileOutputStream fos = new 
      FileOutputStream(entry.getName()); 
      dest = new 
       BufferedOutputStream(fos, BUFFER); 
      while ((count = zis.read(data, 0, BUFFER)) 
       != -1) { 
       dest.write(data, 0, count); 
      } 
      dest.flush(); 
      dest.close(); 
     } 
     zis.close(); 
     } catch(Exception e) { 
     e.printStackTrace(); 
     } 
    } 
} 

Trả lời

13

Vâng, chỉ cần thay đổi phần ghi tệp vào nội dung bạn muốn làm với dữ liệu.

while((entry = zis.getNextEntry()) != null) { 
    System.out.println("Extracting: " + entry); 
    int count; 
    byte data[] = new byte[BUFFER]; 
    string filename = entry.getName(); 
    System.out.println("Filename: " + filename); 
    while ((count = zis.read(data, 0, BUFFER)) != -1) { 
     // Do whatever you want with the data variable 
     System.out.println(data); 
    } 
} 
+0

'byte [] dữ liệu = byte mới [BUFFER];' ?? –

Các vấn đề liên quan