2011-12-27 214 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

相關問題