gpt4 book ai didi

java - 使用 zip 文件的名称命名 Zip 文件夹

转载 作者:行者123 更新时间:2023-12-01 15:37:31 26 4
gpt4 key购买 nike

我正在使用 TarInputStream() 读取 tar 文件的内容并将其中的所有文件存储在特定位置。我想创建一个名称与 tar 文件类似的文件夹,并将所有文件保存在该文件夹中。例如,如果我有一个 tar 文件 test.tar.gz,其中包含文件 test1 和 test2,我的代码应该创建一个名为 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();
}

最佳答案

我会将您的 new File(...) 更改为 new File(dest, tarEntry.getName()); (假设 dest 是一个文件 - 无法看到它来自代码中的位置)。

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

destPath.getParent().mkdirs();

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

要从 lpa_1_454_20111117011749.tar.gz 等获取“基本”lpa_1_454_20111117011749 名称:

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

关于java - 使用 zip 文件的名称命名 Zip 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com