简体   繁体   中英

Get specific file inputstream from TarArchiveInputStream

I have a tar file and which contains many files. I need to get a specific file from tar file and read data from that file.

I am untaring file using the below code and I will read this returned input stream using some other function.

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

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.

The stream you are looking for is the TarArchiveInputStream itself after you've positioned it at the entry you want to read, ie

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

note the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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