2013-03-11 35 views
1

場景:使用Apache commons解壓tar文件。使用apache commons從tar解壓文件 - prob是重複條目

問題:我使用的tar是一個構建tar,它被部署到web服務器中。這個tar包含如下所示的重複條目。

  1. appender_class.xml
  2. APPENDER_CLASS.xml

使用下面的代碼只appender_class.xml被提取,但我想這兩個文件,我怎麼能做到這一點解壓時?在飛行重命名很好,但我怎麼能做到這一點?

public static void untar(File[] files) throws Exception { 
     String path = files[0].toString(); 
     File tarPath = new File(path); 
     TarEntry entry; 
     TarInputStream inputStream = null; 
     FileOutputStream outputStream = null; 
     try { 
      inputStream = new TarInputStream(new FileInputStream(tarPath)); 
      while (null != (entry = inputStream.getNextEntry())) { 
       int bytesRead; 
       System.out.println("tarpath:" + tarPath.getName()); 
       System.out.println("Entry:" + entry.getName()); 
       String pathWithoutName = path.substring(0, path.indexOf(tarPath.getName())); 
       System.out.println("pathname:" + pathWithoutName); 
       if (entry.isDirectory()) { 
        File directory = new File(pathWithoutName + entry.getName()); 
        directory.mkdir(); 
        continue; 
       } 
       byte[] buffer = new byte[1024]; 
       outputStream = new FileOutputStream(pathWithoutName + entry.getName()); 
       while ((bytesRead = inputStream.read(buffer, 0, 1024)) > -1) { 
        outputStream.write(buffer, 0, bytesRead); 
       } 
       System.out.println("Extracted " + entry.getName()); 
      } 
    } 
+1

什麼操作系統?只要您在區分大小寫的文件系統上運行,該代碼應該可以正常工作。 – 2013-03-11 22:09:31

+0

是作爲@mrhobo下面提到的我正在提取一個windows文件系統,其中tar是在UNIX文件系統中創建的。 – Wills 2013-03-12 06:01:14

+1

在不區分大小寫的系統上,不可能創建兩個不同的文件,這兩個文件的名稱只有大小寫不同,因此無法在典型的Windows FS上忠實地提取這樣的tar,因此您必須重命名一個或另一個條目(這取決於tar文件的內容將用於確定這是否安全以及哪個可以更改)。 – 2013-03-12 08:44:53

回答

2

嘗試打開您的FileOutputStream中像這樣來代替:

File outputFile = new File(pathWithoutName + entry.getName()); 
for(int i = 2; outputFile.exists(); i++) { 
    outputFile = new File(pathWithoutName + entry.getName() + i); 
} 
outputStream = new FileOutputStream(outputFile); 

如果遇到所謂APPENDER_CLASS.xml以前創建的文件應該生成一個名爲APPENDER_CLASS.xml2文件。如果APPENDER_CLASS.xml2存在,它將創建一個APPENDER_CLASS.xml3,並且無限。 File.exists()將區分大小寫(Windows文件名不區分大小寫,而unix,linux和mac區分大小寫)。因此,對於不區分大小寫的文件系統的上述代碼,文件將被重命名,並且在區分大小寫的文件系統中文件不會被重命名。

相關問題