如何从ZipInputStream获取每个ZipFile条目的字节/内容,而不必写入outputstream?

4
我正试图从压缩文件输入流中获取特定文件的字节。我有Zipped文件的输入流数据,从这里我获得了ZipEntry并将每个ZipEntry的内容写入输出流并返回字节缓冲区。这将返回缓冲区的输出流大小,但不返回每个特定文件的内容。是否有一种方式可以将FileOutputStream转换为字节或直接读取每个ZipEntry的字节?
我需要将ZipEntry内容作为输出返回,而不是写入文件,只需获取每个zip条目的内容即可。
谢谢您的帮助。
public final class ArchiveUtils {

private static String TEMP_DIR = "/tmp/unzip/";

public static byte[] unZipFromByteStream(byte[] data, String fileName) {

    ZipEntry entry = null;
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data));
    File tempDirectory = ensureTempDirectoryExists(TEMP_DIR);
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (!entry.isDirectory()) {
                System.out.println("-" + entry.getName());

                File file = new File(tempDirectory + "/"+ entry.getName());

                if (!new File(file.getParent()).exists())
                    new File(file.getParent()).mkdirs();
                OutputStream out = new FileOutputStream(entry.getName());
                byte[] byteBuff = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = zis.read(byteBuff)) != -1)
                {
                    out.write(byteBuff, 0, bytesRead);
                }
                out.close();
                if(entry.getName().equals(fileName)){
                return byteBuff;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

private static File ensureTempDirectoryExists(String outputPath) {

    File outputDirectory = new File(outputPath);
    if (!outputDirectory.exists()) {
        outputDirectory.mkdir();
    }
    return outputDirectory;
}

}


3
不要写入FileOutputStream,而是写入ByteArrayOutputStream - Sotirios Delimanolis
2个回答

3

使用java.io.ByteArrayOutputStream,示例如下 -

ByteArrayOutputStream out = null; // outside of your loop (for scope).

// where you have a FileOutputStream.
out = new ByteArrayOutputStream(); // doesn't use entry.getName(). 

然后你就可以

return (out == null) ? null : out.toByteArray();

1
你从ZIP文件中读取文件的方式是,当你从 getNextEntry 获取到的最后一个条目是你想要读取的条目时,你需要从 ZipInputStream 中读取。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接