如何从远程存档文件中提取单个文件? [英] How to extract a single file from a remote archive file?

查看:33
本文介绍了如何从远程存档文件中提取单个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

  1. 存档的 URL(例如 zip 文件)
  2. 该存档中文件的全名(包括路径)

我正在寻找一种方法(最好使用 Java)来创建该文件的本地副本,无需先下载整个存档.

I'm looking for a way (preferably in Java) to create a local copy of that file, without downloading the entire archive first.

从我(有限的)理解来看,这应该是可能的,尽管我不知道该怎么做.我一直在使用 TrueZip,因为它似乎支持多种归档类型,但我有对其以这种方式工作的能力表示怀疑.有没有人有这种事情的经验?

From my (limited) understanding it should be possible, though I have no idea how to do that. I've been using TrueZip, since it seems to support a large variety of archive types, but I have doubts about its ability to work in such a way. Does anyone have any experience with that sort of thing?

能够使用 tarball 和压缩的 tarball 也能做到这一点对我来说也很重要.

being able to also do that with tarballs and zipped tarballs is also important for me.

推荐答案

嗯,至少,您必须下载存档的一部分,包括要提取的文件的压缩数据.这建议了以下解决方案:打开存档的 URLConnection,获取其输入流,将其包装在 ZipInputStream 中,然后重复调用 getNextEntry()closeEntry() 遍历文件中的所有条目,直到找到您想要的条目.然后你可以使用 ZipInputStream.read(...) 读取它的数据.

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(...).

Java 代码如下所示:

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.

这篇关于如何从远程存档文件中提取单个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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