首页 > 解决方案 > 如何将所需文件从 rar 存档直接读取到 InputStream(不提取整个存档)?

问题描述

使用 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 sentence for entry.getName()”行,只是为了表明我只对存档中的某些特定文件感兴趣,并且希望避免将整个存档提取到某个文件夹并稍后删除这些文件。

标签: javarar

解决方案


我现在最终使用这样的东西(使用 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.
         }
    }
}

也许有更好的方法:)


推荐阅读