2009-10-07 2 views
4

내용이 바이트 [] 으로 표시되지만 원래 파일 객체에 액세스 할 수없는 zip 파일이 있습니다.. 각 항목의 내용을 읽고 싶습니다. 바이트의 ByteArrayInputStream에서 ZipInputStream을 만들 수 있으며 항목과 해당 이름을 읽을 수 있습니다. 그러나 각 항목의 내용을 추출하는 쉬운 방법을 볼 수 없습니다.바이트 []에서 읽을 때 ZipFile 항목의 내용을 추출 할 때 (자바)

(나는 Apache Commons를 살펴 봤지만 거기에서도 쉽게 볼 수는 없다). 모두 예 (512분의 128 1024 * 4) * 4의 승수가 왜 리치의 코드 @

UPDATE 감사

QUERY, 문제를 해결하는 것?

답변

6

스트림에서 중첩 된 zip 항목을 처리하려면 this answer을 참조하십시오. 내부 항목은 순차적으로 나열되기 때문에 각 항목의 크기를 가져 와서 스트림에서 많은 바이트를 읽음으로써 처리 할 수 ​​있습니다.

는 예와 업데이트를 복사 표준 출력에 각 항목 :

ZipInputStream is;//obtained earlier 

ZipEntry entry = is.getNextEntry(); 

while(entry != null) { 
    copyStream(is, out, entry); 

    entry = is.getNextEntry(); 
} 
... 

private static void copyStream(InputStream in, OutputStream out, 
     ZipEntry entry) throws IOException { 
    byte[] buffer = new byte[1024 * 4]; 
    long count = 0; 
    int n = 0; 
    long size = entry.getSize(); 
    while (-1 != (n = in.read(buffer)) && count < size) { 
     out.write(buffer, 0, n); 
     count += n; 
    } 
} 
+0

@Rich에 포함되어 있습니다. zip 파일에 액세스 할 수 없도록 지정했습니다. 중첩 된 zip이 없습니다. –

+0

어떻게 대답 할 수 있는지 설명하기 위해 답을 업데이트했습니다. 스트림 –

+0

@ 리치에서 각 항목의 크기를 읽을 수있는 단일 스트림이 있습니다. 고마워. 내가 그 크기를 읽으려고 노력할거야. –

0

그것은 실제로 InputStreamZipInputStream을 사용합니다 (그러나 각 항목의 끝 부분을 닫지 마십시오).

0

다음 ZipEntry의 시작을 계산하는 것은 약간 까다 롭습니다. 이 예제는 JDK 6,

public static void main(String[] args) { 
    try { 
     ZipInputStream is = new ZipInputStream(System.in); 
     ZipEntry ze; 
     byte[] buf = new byte[128]; 
     int len; 

     while ((ze = is.getNextEntry()) != null) { 
      System.out.println("----------- " + ze); 

      // Determine the number of bytes to skip and skip them. 
      int skip = (int)ze.getSize() - 128; 
      while (skip > 0) { 
       skip -= is.skip(Math.min(skip, 512)); 
      } 

      // Read the remaining bytes and if it's printable, print them. 
      out: while ((len = is.read(buf)) >= 0) { 
       for (int i=0; i<len; i++) { 
        if ((buf[i]&0xFF) >= 0x80) { 
         System.out.println("**** UNPRINTABLE ****"); 

         // This isn't really necessary since getNextEntry() 
         // automatically calls it. 
         is.closeEntry(); 

         // Get the next zip entry. 
         break out; 
        } 
       } 
       System.out.write(buf, 0, len); 
      } 
     } 
     is.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
관련 문제