简体   繁体   English

从 TarArchiveInputStream 获取特定的文件输入流

[英]Get specific file inputstream from TarArchiveInputStream

I have a tar file and which contains many files.我有一个 tar 文件,其中包含许多文件。 I need to get a specific file from tar file and read data from that file.我需要从 tar 文件中获取特定文件并从该文件中读取数据。

I am untaring file using the below code and I will read this returned input stream using some other function.我正在使用下面的代码解压文件,我将使用其他一些 function 读取这个返回的输入 stream。

 private  InputStream unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {
        InputStream versionInputStream = null;
        final InputStream is = new FileInputStream(inputFile); 
        final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null; 
        while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {
            if (!entry.isDirectory() && entry.getName().equals("version.txt")) {
                versionInputStream =  new FileInputStream(entry.getFile());
            }     
        }
        return versionInputStream;
    }

I get null pointer exception when i do versionInputStream = new FileInputStream(entry.getFile());当我执行versionInputStream = new FileInputStream(entry.getFile());

I know that we can first save this file in directory and then read the file but i dont want to save this file in directory.我知道我们可以先将此文件保存在目录中,然后再读取文件,但我不想将此文件保存在目录中。

Is there some way I can read this file without saving the file to some dir?有什么方法可以在不将文件保存到某个目录的情况下读取此文件?

There is no file for an entry of an archive you read.您阅读的存档条目没有文件。 TarArchiveEntry 's getFile method only returns anything useful when the entry has been created with a File -arg constructor, which only makes sense when creating an archive not reading it. TarArchiveEntrygetFile方法仅在使用File -arg 构造函数创建条目时返回任何有用的内容,这仅在创建存档而不读取它时才有意义。

The stream you are looking for is the TarArchiveInputStream itself after you've positioned it at the entry you want to read, ie您正在寻找的 stream 是TarArchiveInputStream本身,在您将其定位在您要阅读的条目之后,即

            if (!entry.isDirectory() && entry.getName().equals("version.txt")) {
                versionInputStream = debInputStream;
                break;
            }

note the break .注意break

The not-yet-released (an no, no release date, yet) Commons Compress 1.21 will contain a new TarFile class that provides random-access to archives read from a seekable source (like a File ) and will make your task more convenient.尚未发布(还没有发布日期)Commons Compress 1.21 将包含一个新的TarFile class ,它提供对从可搜索源(如File )读取的档案的随机访问,并使您的任务更方便。

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

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