2016-04-11 2 views
4

У меня есть байты [] zipFileAsByteArrayчтение Zip содержимого файл без извлечения в Java

This zip file has rootDir --| 
          | --- Folder1 - first.txt 
          | --- Folder2 - second.txt 
          | --- PictureFolder - image.png 

Что мне нужно, чтобы получить две текстовые файлы и читать их, без сохранения файлов на диске. Просто сделайте это в памяти.

Я пытался что-то вроде этого:

ByteArrayInputStream bis = new ByteArrayInputStream(processZip); 
ZipInputStream zis = new ZipInputStream(bis); 

Кроме того, мне нужно будет иметь отдельный метод пойти получить картину. Что-то вроде этого:

public byte[]image getImage(byte[] zipContent); 

Может кто-то помочь мне с идеей или хорошим примером, как это сделать?

+0

Я думаю, что то, что вы ищете, можно найти по адресу: http://stackoverflow.com/questions/15667125/read-content-from-files-which -Есть-внутри-зип-файл. Для чего это относится к изображению, вы должны иметь возможность сделать это, глядя на следующее: http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/. Чтобы определить, следует ли вызвать метод getImage, проверьте расширение файла. – LoreV

ответ

1

Вот пример:

public static void main(String[] args) throws IOException { 
    ZipFile zip = new ZipFile("C:\\Users\\mofh\\Desktop\\test.zip"); 


    for (Enumeration e = zip.entries(); e.hasMoreElements();) { 
     ZipEntry entry = (ZipEntry) e.nextElement(); 
     if (!entry.isDirectory()) { 
      if (FilenameUtils.getExtension(entry.getName()).equals("png")) { 
       byte[] image = getImage(zip.getInputStream(entry)); 
       //do your thing 
      } else if (FilenameUtils.getExtension(entry.getName()).equals("txt")) { 
       StringBuilder out = getTxtFiles(zip.getInputStream(entry)); 
       //do your thing 
      } 
     } 
    } 


} 

private static StringBuilder getTxtFiles(InputStream in) { 
    StringBuilder out = new StringBuilder(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
    String line; 
    try { 
     while ((line = reader.readLine()) != null) { 
      out.append(line); 
     } 
    } catch (IOException e) { 
     // do something, probably not a text file 
     e.printStackTrace(); 
    } 
    return out; 
} 

private static byte[] getImage(InputStream in) { 
    try { 
     BufferedImage image = ImageIO.read(in); //just checking if the InputStream belongs in fact to an image 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ImageIO.write(image, "png", baos); 
     return baos.toByteArray(); 
    } catch (IOException e) { 
     // do something, it is not a image 
     e.printStackTrace(); 
    } 
    return null; 
} 

Имейте в виду, хотя я проверяю строку diferentiate возможные типы и это чревато ошибками. Ничто не мешает мне отправлять другой тип файла с ожидаемым расширением.

+0

У меня нет ZipFile zip = new ZipFile («C: \\ Users \\ mofh \\ Desktop \\ test.zip»); моя запись ZipInputStream zis = новый ZipInputStream (бис); – TNN

+0

Просто используйте его тогда ... Если у вас есть байт [] для zip, просто 'ZipFile zip = new ZipInputStream (новый ByteArrayInputStream (processZip))'. – dambros

1

Вы можете сделать что-то вроде:

public static void main(String args[]) throws Exception 
{ 
    //bis, zis as you have 
    try{ 
     ZipEntry file; 
     while((file = zis.getNextEntry())!=null) // get next file and continue only if file is not null 
     { 
      byte b[] = new byte[(int)file.getSize()]; // create array to read. 
      zis.read(b); // read bytes in b 
      if(file.getName().endsWith(".txt")){ 
       // read files. You have data in `b` 
      }else if(file.getName().endsWith(".png")){ 
       // process image 
      } 
     } 
    } 
    finally{ 
     zis.close(); 
    } 
} 
+0

file.getSize() return -1; – TNN

Смежные вопросы