如何在Java中的ZIP文件中创建ZIP文件

时间:2017-11-15 01:35:22

标签: java zip unzip

我正在尝试在ZIP文件中创建一个ZIP文件,以重新构建我之前使用Java编写的内存zip结构。

我失败了,因为我在初始ZIP文件中创建的内部ZIP上出现错误。该文件已损坏。尝试打开文件时,我收到“意外的文件结尾”

我有这个结构:

-input.zip --innerInput.zip

Code使用java Stack和Map将其全部解压缩到内存中。然后它创建input2.zip,其中包含innerInput.zip。

总结:我需要创建一个带有ZIP的ZIP,全部都在内存中(暂时不保存在磁盘上)。

CODE:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.lang3.StringUtils;

public class ZipHandler1 {

    private static final int BUFFER_SIZE = 2048;

    private static final String ZIP_EXTENSION = ".zip";
    public static final Integer FOLDER = 1;
    public static final Integer ZIP = 2;
    public static final Integer FILE = 3;


    public static Deque<Map<Integer, Object[]>> unzip(ByteArrayOutputStream zippedOutputFile) {

        try {

            ZipInputStream inputStream = new ZipInputStream(
          new BufferedInputStream(new ByteArrayInputStream(
              zippedOutputFile.toByteArray())));

            ZipEntry entry;

            Deque<Map<Integer, Object[]>> result = new ArrayDeque<Map<Integer, Object[]>>();

            while ((entry = inputStream.getNextEntry()) != null) {

                LinkedHashMap<Integer, Object[]> map = new LinkedHashMap<Integer, Object[]>();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                System.out.println("\tExtracting entry: " + entry);
                int count;
                byte[] data = new byte[BUFFER_SIZE];
                if (!entry.isDirectory()) {
                    BufferedOutputStream out = new BufferedOutputStream(
          outputStream, BUFFER_SIZE);

                while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }

                out.flush();
                out.close();

                //  recursively unzip files
                if (entry.getName().toUpperCase().endsWith(ZIP_EXTENSION.toUpperCase())) {
                map.put(ZIP, new Object[] {entry.getName(), unzip(outputStream)});
                result.add(map);

                } else { 
                    map.put(FILE, new Object[] {entry.getName(), outputStream});
                    result.add(map);
                }
                } else {
                    map.put(FOLDER, new Object[] {entry.getName(), 
                    unzip(outputStream)});
                    result.add(map);
                }
            }

        inputStream.close();

        return result;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

package course.hernan;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

public class FileReader {

  private static final int  BUFFER_SIZE = 2048;

  public static void main(String[] args) {

    try {
      File f = new File("DIR/inputs.zip");
      FileInputStream fis = new FileInputStream(f);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      BufferedOutputStream bos = new BufferedOutputStream(baos);
      byte[] buffer = new byte[BUFFER_SIZE];

      while (bis.read(buffer, 0, BUFFER_SIZE) != -1) {
        bos.write(buffer);
      }

      bos.flush();
      bos.close();
      bis.close();

      Deque<Map<Integer, Object[]>> outputDataStack = ZipHandler1.unzip(baos);

      //Output file
      File fout = new File("DIR/inputs2.zip");

      ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(fout)));

      processZip(outputDataStack, zipOutput);
      zipOutput.close();

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
}

private static final void processZip(Deque<Map<Integer, Object[]>> outputDataStack, 
  ZipOutputStream zipOutput) throws IOException {

while (!outputDataStack.isEmpty()) {
    Map<Integer, Object[]> map = outputDataStack.pop();

    for (Map.Entry<Integer, Object[]> entry : map.entrySet()) {
        System.out.println("KEY:" + entry.getKey());
        Object[] values = entry.getValue();
        String entryName = (String)values[0];

        if (entry.getKey().equals(ZipHandler1.FILE)) {
            System.out.println("..........................");
            System.out.println("type: FILE");
            System.out.println("Name: " + entryName);

            zipOutput.putNextEntry(new ZipEntry(entryName));
            byte[] outputByteArray = ((ByteArrayOutputStream)values[1]).toByteArray();

            IOUtils.write(outputByteArray, zipOutput);
            zipOutput.closeEntry();
            ((ByteArrayOutputStream)values[1]).close();

        } else if (entry.getKey().equals(ZipHandler1.FOLDER)) {
            System.out.println("..........................");
            System.out.println("type: FOLDER");
            System.out.println("Name: " + entryName);

            zipOutput.putNextEntry(new ZipEntry(entryName));
            System.out.println("..........................");
            zipOutput.closeEntry();

        } else if (entry.getKey().equals(ZipHandler1.ZIP)) {
            System.out.println("..........................");
            System.out.println("type: ZIP");
            System.out.println("Name: " + entryName);

            zipOutput.putNextEntry(new ZipEntry(entryName));

            ByteArrayOutputStream innerZipByteArray = new ByteArrayOutputStream(BUFFER_SIZE);
            ZipOutputStream innerZipOutput = new ZipOutputStream(
          new BufferedOutputStream(innerZipByteArray));

            processZip((Deque<Map<Integer,Object[]>>)values[1], innerZipOutput);
            innerZipOutput.flush();
            IOUtils.write(zzzz.toByteArray(), zipOutput);
            innerZipOutput.close();
            zipOutput.closeEntry();
            System.out.println("..........................");
        }
            System.out.println("..........................");
            zipOutput.closeEntry();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

感谢我!

我很难找到答案,对其他人来说可能很明显。

简短回答:我正在关闭内部邮政流程

好的,问题是在ZIP中存储ZIP吗? 好吧,我收到一个错误,因为内部拉链太快关闭了

解决方案:

像这样创建内部zip文件:     ByteArrayOutputStream innerZipBufferOutput = new ByteArrayOutputStream(BUFFER_SIZE);     ZipOutputStream innerZipOutput = new ZipOutputStream(               new BufferedOutputStream(innerZipBufferOutput));

将字节(info)写入内部zip

关闭内部拉链流     innerZipOutput.close(); **这是我在错误的时间关闭*

此时,字节形式的数据位于 innerZipBufferOutput

在外部zip文件中为内部zip文件设置条目

ZipEntry newEntry = new ZipEntry(entryName);
zipOutput.putNextEntry(newEntry);  

将内部拉链写入外部拉链

zipOutput.write(innerZipBufferOutputByteArray);

关闭外拉链

zipOutput.flush();
zipOutput.closeEntry();

瞧!

示例(代码提取) - 你有一个ZipOutputStream(外部zip文件)

ByteArrayOutputStream innerZipBufferOutput = new ByteArrayOutputStream(BUFFER_SIZE);
ZipOutputStream innerZipOutput = new ZipOutputStream(new BufferedOutputStream(innerZipBufferOutput)); 

<<process - e.g. create your inner zip file>>

innerZipOutput.flush();
innerZipOutput.close();

ZipEntry newEntry = new ZipEntry(<<your entry name>>); 

zipOutput.setMethod(ZipOutputStream.STORED);

byte[] innerZipBufferOutputByteArray = innerZipBufferOutput.toByteArray();

//Create the nested ZIP inside the outer ZIP 
ZipEntry newEntry = new ZipEntry(entryName); 
zipOutput.putNextEntry(newEntry);

zipOutput.write(innerZipBufferOutputByteArray);


zipOutput.closeEntry();
zipOutput.close();