Use common compression to read tar. In Java gz
•
Java
OK, I want to read tar GZ file (or XY), but this is one thing
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) { File f = currentEntry.getFile(); br = new BufferedReader(new FileReader(f)); System.out.println("For File = " + currentEntry.getName()); String line; while ((line = br.readLine()) != null) { System.out.println("line="+line); } } if (br!=null) { br.close(); }
But when I call the GetFile method of tararchiveentry, I get null I am using Apache commons compress 1.8 one
Solution
You cannot use GetFile. For tararchiveentry When you compress a file in a tar file, that getter is only used for the opposite operation
Instead, you should read directly from tararchiveinputstream It will be responsible for returning "dynamically" decompressing the contents of its "file"
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 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码