0

我正在使用 TarInputStream() 读取 tar 文件的内容并将其中的所有文件存储在特定位置。我想创建一个名称类似于 tar 文件的文件夹,并将我的所有文件保存在该文件夹中。例如,如果我有一个包含文件 test1 和 test2 的 tar 文件 test.tar.gz,我的代码应该创建一个名为 test 的文件夹并将 tar 文件解压缩到该文件夹​​。

这是我写的代码。

TarInputStream tin = new TarInputStream(new GZIPInputStream(new FileInputStream(new File(tarFileName))));

TarEntry tarEntry = tin.getNextEntry();
        while (tarEntry != null) {// create a file with the same name as tar entry

            File destPath = new File(dest.toString() + File.separatorChar
                    + tarEntry.getName());

            FileOutputStream fout = new FileOutputStream(destPath);
                tin.copyEntryContents(fout);
                fout.close();
                ///services/advert/lpa/dimenions/data/advertiser/
                Path inputFile = new Path(destPath.getAbsolutePath());

                //To remove the local files set the flag to true
                fs.copyFromLocalFile(inputFile, filenamepath); 
                tarEntry = tin.getNextEntry();
}
4

1 回答 1

1

我会将您更改new File(...)new File(dest, tarEntry.getName());(假设destFile- 在您的代码中看不到它的来源)。

最重要的是,您需要确保您正在创建要在其中创建文件的目录。这可以通过以下方式完成:

destPath.getParent().mkdirs();

.getParent()很重要,因为我们不能为文件名的每个部分创建一个文件夹,否则文件名也会被创建为文件夹而不是文件,然后尝试向其中写入数据会失败(因为文件会预期而不是存在的文件夹)。

从以下内容获取“基本”lpa_1_454_20111117011749名称lpa_1_454_20111117011749.tar.gz

String tarFileName = "/tmp/lpa_1_454_20111117011749.tar.gz";

// Non-regular expression approach:
{
    int lastPath = tarFileName.lastIndexOf('/');
    if(lastPath >= 0){
        lastPath++;
    }
    int endName = tarFileName.length();
    if(tarFileName.endsWith(".tar.gz")){
        endName -= 7;
    }

    String baseName = tarFileName.substring(lastPath, endName);
    System.out.println(baseName);
}

// Regular expression approach:
{
    Pattern p = Pattern.compile("(?:.*/|^)(.*)\\.tar\\.gz");
    Matcher m = p.matcher(tarFileName);
    if(m.matches()){
        System.out.println(m.group(1));
    }
}

两种方法都输出:

lpa_1_454_20111117011749
于 2011-12-27T20:33:37.727 回答