简体   繁体   English

如何将需要的文件从 rar 存档直接读取到 InputStream(不提取整个存档)?

[英]How to read needed files from rar archive directly to InputStream (without extracting whole archive)?

Seems quite simple with zip archive using java.util.zip.ZipFile like this:使用 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.
            }
        }
    }
}

What would be the alternative for rar archives? rar 档案的替代方案是什么?

I'm aware of Junrar, but didn't found a way to do it without extracting whole archive to some folder.我知道 Junrar,但没有找到不将整个存档解压缩到某个文件夹的方法。

Edit:编辑:

I have added "if sentence for entry.getName()" line just to indicate what I'm interested only in some specific files inside archive and would like to avoid extracting whole archive to some folder and later deleting those files.我添加了“if sentence for entry.getName()”行只是为了表明我只对存档中的某些特定文件感兴趣,并希望避免将整个存档提取到某个文件夹,然后再删除这些文件。

I end up using something like this for now (with Junrar):我现在最终使用了这样的东西(使用 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.
         }
    }
}

Maybe there is a better way :)也许有更好的方法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM