2011-12-27 321 views
0

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

这是我写的代码。

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(); 
} 

回答

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 
+0

字符串tarFileName = “/ TMP/lpa_1_454_20111117011749.tar.gz”; File dest = new File(“/ tmp/test /”); 所以,我想要在文件夹名称lpa_1_454_20111117011749下提取所有文件。但是我无法提取这个名字! – RFT 2011-12-27 20:47:27

+0

你的代码结合这个答案应该可以达到你的期望。你能否详细说明“无法提取该名称”的含义?假设'lpa _...'是TAR文件中的文件名,应该由'tarEntry.getName()'返回,并导致'/ tmp/test/tmp/lpa _...“的'destPath'。当然,这里有第二个“tmp”,但这是做这个的唯一“安全”方式 - 除非您提供从TAR文件名剥离已知数量的路径组件的选项 - 但这会让一些漂亮关于您期望处理的每个TAR文件的严重假设。 – ziesemer 2011-12-27 20:52:50

+0

lpa_ ..是我从中提取文件的tar文件。我可以使用tarEntry.getName()提取文件的名称,但不能提取tar文件的名称lpa _... – RFT 2011-12-27 20:57:35

相关问题