Read tar.gz in Java with Commons-compression

前端 未结 1 1233
眼角桃花
眼角桃花 2020-12-10 05:41

Ok so I want to read the contents of a tar.gz file (or a xy) but that\'s the same thing. What I am doing is more or less this:

TarArchiveInputStream tarInput         


        
相关标签:
1条回答
  • 2020-12-10 06:06

    You can't use the getFile of TarArchiveEntry. That getter is there only for the opposite operation, when you are compressing files inside a tar file.

    Instead, you should read directly from TarArchiveInputStream. It will take care of returning you the content of the "file" decompressing it on the fly.

    For example (untested code, YMMV) :

    TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream("c://temp//test.tar.gz")));
    TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();
    while (currentEntry != null) {
        br = new BufferedReader(new InputStreamReader(tarInput)); // Read directly from tarInput
        System.out.println("For File = " + currentEntry.getName());
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("line="+line);
        }
        currentEntry = tarInput.getNextTarEntry(); // You forgot to iterate to the next file
    }
    
    0 讨论(0)
提交回复
热议问题