JTar从.tar文件中提取文件

时间:2012-07-24 17:45:42

标签: java tar

我正在使用jtar-1.1尝试从tar文件中提取文件,我使用以下代码尝试提取文件

String tarFile = "c:/test/test.tar";
String destFolder = "c:/test/myfiles";

// Create a TarInputStream
TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
while (( entry = tis.getNextEntry() ) != null) {
        System.out.println( "Extracting: " + entry.getName() );
        int count;
        byte data[] = new byte[BUFFER];

        if (entry.isDirectory()) {
            new File( destFolder + "/" + entry.getName() ).mkdirs();
            continue;
        } else {
            int di = entry.getName().lastIndexOf( '/' );
            if (di != -1) {
                new File( destFolder + "/" + entry.getName().substring( 0, di ) ).mkdirs();
            }
        }

        FileOutputStream fos = new FileOutputStream( destFolder + "/" + entry.getName() );
        BufferedOutputStream dest = new BufferedOutputStream( fos );

        while (( count = tis.read( data ) ) != -1) {
            dest.write( data, 0, count );
        }

        dest.flush();
        dest.close();
    }
}

编辑:

我已经编辑了上面的代码以检查是entry a directory,一旦我这样做了它就摆脱了FileNotFound错误......上面的代码现在正常工作

2 个答案:

答案 0 :(得分:3)

我认为您需要在打开FileOutputStream之前创建路径。

类似帖子Here

答案 1 :(得分:1)

关闭袖口,也许问题是你收到的条目包含一个尚未创建的子文件夹:'LAB3'?在这种情况下,文件系统中不存在目录“LAB3”,因为您尚未创建目录,并且文件“sg5”打算放在那里,因此当您尝试在包含LAB3的完全限定路径上创建文件时它抱怨。

相关问题