在 java (JSP) 中提取 .tar.gz 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14402598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:09:25  来源:igfitidea点击:

Extract a .tar.gz file in java (JSP)

javajspextracttarapache-commons

提问by FredoAF

I can't seem to import the packages needed or find any online examples of how to extract a .tar.gzfile in java.

我似乎无法导入所需的包,也无法找到有关如何.tar.gz在 java 中提取文件的任何在线示例。

What makes it worse is I'm using JSP pages and am having trouble importing packages into my project. I'm copying the .jar's into WebContent/WEB-INF/lib/and then right clicking on the project and selecting import external jar and importing it. Sometimes the packages resolve, other times they don't. Can't seem to get GZIP to import either. The imports in eclipse for jsp aren't intuitive like they are in normal Java code where you can right click a recognized package and select import.

更糟糕的是我正在使用 JSP 页面并且在将包导入我的项目时遇到问题。我正在将 .jar 复制到其中WebContent/WEB-INF/lib/,然后右键单击该项目并选择导入外部 jar 并导入它。有时包会解析,有时不会。似乎也无法导入 GZIP。Eclipse 中用于 jsp 的导入不像在普通 Java 代码中那样直观,您可以在其中右键单击已识别的包并选择导入。

I've tried the Apache commons library, the ice and another one called JTar. Ice has imported, but I can't find any examples of how to use it?

我已经尝试了 Apache 公共库、ice 和另一个名为 JTar 的库。Ice 已经导入了,但是我找不到任何如何使用它的示例?

I guess I need to uncompress the gzipped part first, then open it with the tarstream?

我想我需要先解压缩 gzipped 部分,然后用 tarstream 打开它?

Any help is greatly appreciated.

任何帮助是极大的赞赏。

采纳答案by FredoAF

Ok, i finally figured this out, here is my code in case this helps anyone in the future. Its written in Java, using the apache commons io and compress librarys.

好的,我终于想通了,这是我的代码,以防将来对任何人有所帮助。它是用 Java 编写的,使用 apache commons io 和压缩库。

File dir = new File("directory/of/.tar.gz/files/here");
File listDir[] = dir.listFiles();
if (listDir.length!=0){
    for (File i:listDir){
        /*  Warning! this will try and extract all files in the directory
            if other files exist, a for loop needs to go here to check that
            the file (i) is an archive file before proceeding */
        if (i.isDirectory()){
            break;
        }
        String fileName = i.toString();
        String tarFileName = fileName +".tar";
        FileInputStream instream= new FileInputStream(fileName);
        GZIPInputStream ginstream =new GZIPInputStream(instream);
        FileOutputStream outstream = new FileOutputStream(tarFileName);
        byte[] buf = new byte[1024]; 
        int len;
        while ((len = ginstream.read(buf)) > 0) 
        {
            outstream.write(buf, 0, len);
        }
        ginstream.close();
        outstream.close();
        //There should now be tar files in the directory
        //extract specific files from tar
        TarArchiveInputStream myTarFile=new TarArchiveInputStream(new FileInputStream(tarFileName));
        TarArchiveEntry entry = null;
        int offset;
        FileOutputStream outputFile=null;
        //read every single entry in TAR file
        while ((entry = myTarFile.getNextTarEntry()) != null) {
            //the following two lines remove the .tar.gz extension for the folder name
            String fileName = i.getName().substring(0, i.getName().lastIndexOf('.'));
            fileName = fileName.substring(0, fileName.lastIndexOf('.'));
            File outputDir =  new File(i.getParent() + "/" + fileName + "/" + entry.getName());
            if(! outputDir.getParentFile().exists()){ 
                outputDir.getParentFile().mkdirs();
            }
            //if the entry in the tar is a directory, it needs to be created, only files can be extracted
            if(entry.isDirectory){
                outputDir.mkdirs();
            }else{
                byte[] content = new byte[(int) entry.getSize()];
                offset=0;
                myTarFile.read(content, offset, content.length - offset);
                outputFile=new FileOutputStream(outputDir);
                IOUtils.write(content,outputFile);  
                outputFile.close();
            }
        }
        //close and delete the tar files, leaving the original .tar.gz and the extracted folders
        myTarFile.close();
        File tarFile =  new File(tarFileName);
        tarFile.delete();
    }
}

回答by simpletron

The accepted answer works fine, but I think it is redundant to have a write to file operation.

接受的答案工作正常,但我认为写入文件操作是多余的。

You could use something like

你可以使用类似的东西

 TarArchiveInputStream tarInput = 
      new TarArchiveInputStream(new GZipInputStream(new FileInputStream("Your file name")));

 TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
 while(currentEntry != null) {
      File f = currentEntry.getFile();
      // TODO write to file as usual
 }

Hope this help.

希望这有帮助。

Maven Repo

Maven仓库