【问题标题】:How to read needed files from rar archive directly to InputStream (without extracting whole archive)?如何将所需文件从 rar 存档直接读取到 InputStream(不提取整个存档)?
【发布时间】:2020-05-15 08:07:44
【问题描述】:

使用 java.util.zip.ZipFile 的 zip 存档看起来很简单,如下所示:

public static void main(String[] args) throws IOException 
{
    final ZipFile zipFile = new ZipFile("C:/test.zip");

    final Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements())
    {
        final ZipEntry entry = entries.nextElement();

        if(entry.getName().equals("NEEDED_NAME"))
        {
            try(InputStream inputStream = zipFile.getInputStream(entry))
            {
                // Do what's needed with the inputStream.
            }
        }
    }
}

rar 档案的替代方案是什么?

我知道 Junrar,但没有找到不将整个存档解压缩到某个文件夹的方法。

编辑:

我添加了“if 语句 for entry.getName()”行只是为了表明我只对存档中的某些特定文件感兴趣,并且希望避免将整个存档提取到某个文件夹然后删除这些文件。

【问题讨论】:

  • 请注意,此代码将在您阅读时提取 zip。不可能“不提取就阅读”。它只是对你隐藏了这个事实。
  • 哦,我明白了。然后,我正在寻找 rar 的替代方法(无需显式提取到特定文件夹)。它应该像 zip 示例一样“在窗帘下”完成这项工作。
  • 我也可以使用 entry.getName() 来定位只需要的文件,这就是我最想做的事情。我会稍微更新一下这个例子。它应该比提取整个档案快得多。
  • RAR 不是标准文件格式,核心 Java 库不支持它们。寻找第三方 RAR 库
  • 我正在查看第三方库(如 Junrar 和其他库),但如果不将整个存档提取到特定文件夹(我不需要),我看不到这样做的方法。

标签: java rar


【解决方案1】:

我现在最终使用这样的东西(使用 Junrar):

final Archive archive = new Archive(new File("C:/test.rar"), null);

final LocalFolderExtractor lfe = new LocalFolderExtractor(new File("/path/to/temp/location/"), new FileSystem());

for (final FileHeader fileHeader : archive)
{
    if(fileHeader.getFileNameString().equals("NEEDED_NAME"))
    {
         File file = null;

         try
         {
             file = lfe.extract(archive, fileHeader);

             // Create inputStream from file and do what's needed.
         }
         finally
         {
             // Fully delete the file + folders if needed.
         }
    }
}

也许有更好的方法:)

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 2011-02-28
    • 2014-06-25
    • 2015-06-27
    • 2017-09-17
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多