How to read content of the Zipped file without extracting in java

前端 未结 3 867
傲寒
傲寒 2020-12-18 07:49

I have file with names like ex.zip. In this example, the Zip file contains only one file with the same name(ie. `ex.txt\'), which is quite large. I don\'t want

相关标签:
3条回答
  • 2020-12-18 08:27

    I think that in your case the fact that a zipfile is a container that can hold many files (and thus forces you to navigate to the right contained file each time you open it) seriously complicates things, as you state that each zipfile only contains one textfile. Maybe it's a lot easier to just gzip the text file (gzip is not a container, just a compressed version of your data). And it's very simple to use:

    GZIPInputStream gis = new GZIPInputStream(new FileInputStream("file.txt.gz"));
    // and a BufferedReader on top to comfortably read the file
    BufferedReader in = new BufferedReader(new InputStreamReader(gis) );
    

    Producing them is equally simple:

    GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("file.txt.gz"));
    
    0 讨论(0)
  • 2020-12-18 08:28

    Your idea is to read the zip file as it is into a byte array and store it in a variable. Later when you need the zip you extract it on demand, saving memory:

    First read the content of the Zip file in a byte array zipFileBytes

    If you have Java 1.7:

    Path path = Paths.get("path/to/file");
    byte[] zipFileBytes= Files.readAllBytes(path);
    

    otherwise use Appache.commons lib

    byte[] zipFileBytes;
    zipFileBytes = IOUtils.toByteArray(InputStream input);
    

    Now your Zip file is stored in a variable zipFileBytes, still in compressed form.

    Then when you need to extract something use

    ByteArrayInputStream bis = new ByteArrayInputStream(zipFileBytes));
    ZipInputStream zis = new ZipInputStream(bis);
    
    0 讨论(0)
  • 2020-12-18 08:44

    Try this:

            ZipFile fis = new ZipFile("ex.zip");
    
            int i = 0;
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                System.out.println(entry);
                System.out.println(i);
    
                InputStream in = fis.getInputStream(entry);
    
            }
    

    For example, if the file contains text, and you want to print it as a String, you can read the InputStream like this: Read/convert an InputStream to a String

    0 讨论(0)
提交回复
热议问题