How to extract a single file from a remote archive file?

前端 未结 4 1377
广开言路
广开言路 2020-12-05 20:29

Given

  1. URL of an archive (e.g. a zip file)
  2. Full name (including path) of a file inside that archive

I\'m looking for a way (preferably i

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 20:48

    Well, at a minimum, you have to download the portion of the archive up to and including the compressed data of the file you want to extract. That suggests the following solution: open a URLConnection to the archive, get its input stream, wrap it in a ZipInputStream, and repeatedly call getNextEntry() and closeEntry() to iterate through all the entries in the file until you reach the one you want. Then you can read its data using ZipInputStream.read(...).

    The Java code would look something like this:

    URL url = new URL("http://example.com/path/to/archive");
    ZipInputStream zin = new ZipInputStream(url.getInputStream());
    ZipEntry ze = zin.getNextEntry();
    while (!ze.getName().equals(pathToFile)) {
        zin.closeEntry(); // not sure whether this is necessary
        ze = zin.getNextEntry();
    }
    byte[] bytes = new byte[ze.getSize()];
    zin.read(bytes);
    

    This is, of course, untested.

提交回复
热议问题