无需在java中提取即可读取Zip文件内容 [英] Read Zip file content without extracting in java

查看:33
本文介绍了无需在java中提取即可读取Zip文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字节[] zipFileAsByteArray

I have byte[] zipFileAsByteArray

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

我需要的是获取两个 txt 文件并读取它们,而无需在磁盘上保存任何文件.只需在内存中执行即可.

What I need is to get two txt files and read them, without saving any files on disk. Just do it in memory.

我尝试过这样的事情:

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

另外,我需要有单独的方法去获取图片.像这样:

Also I will need to have separate method go get picture. Something like this:

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

有人可以帮我提供想法或很好的例子吗?

推荐答案

这是一个例子:

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;
}

请记住,虽然我正在检查一个字符串以区分可能的类型,但这很容易出错.没有什么能阻止我发送具有预期扩展名的另一种类型的文件.

Keep in mind though I am checking a string to diferentiate the possible types and this is error prone. Nothing stops me from sending another type of file with an expected extension.

这篇关于无需在java中提取即可读取Zip文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆