0

I have seen many Java tutorial that explains how to uncompress a zip file to disk. But I was wondering if it was possible to extract a file into memory.

For example, I will have multiple zip files to read which each contains a JSON file with some information. I want to pass into each zip file and extract the information from the JSON file.

Now with what I currently know, I would need to extract the JSON file to disk, read the JSON file from disk, delete the JSON file and then repeat with the next zip file.

Is there a way to extract a zip entry into a memory object, and read the JSON file from memory.

In fact what I would need is a file handle pointing to an in-memory file extracted from the zip archive.

larienna
  • 151
  • 4
  • 12
  • Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions. –  Nov 07 '17 at 14:53

1 Answers1

2

Zip file does not need be to extracted anywhere. You can read directly from the archive. Try something like that (everything is plain Java, no external library is needed):

    ZipFile zipFile = new ZipFile("archive.zip");
    ZipEntry entry = zipFile.getEntry("file.json");
    InputStream is = zipFile.getInputStream(entry);
    byte[] data = new byte[is.available()];
    is.read(data);
    String json = new String(data);
mjjaniec
  • 793
  • 1
  • 8
  • 19
  • Hmm! so you convert the whole stream into a table of byte, and then convert it to string. All code example, load chunks of 1024 bytes at a time, I did not know you could load everything at once. – larienna Oct 25 '15 at 03:00
  • I also need to load a picture icon, I am using libGDX, and I saw that Pixmap has a constructor to load from bytes "Pixmap(byte[] encodedData, int offset, int len)", I imagine I could use the same process than the above for pictures. – larienna Oct 25 '15 at 03:02
  • @larienna The examples you saw before are right of course, because in general case you cannot assume that file you read is small enough to fit into memory. But since it was JSON data I made such assumption. And I think it would work with Pixmap also. – mjjaniec Oct 25 '15 at 08:03