2015-10-24 134 views
0

我一直在嘗試整個上午,我無法弄清楚這一點!我立足我的代碼關閉this sample將文件夾寫入JAR文件

public void run() throws IOException 
{ 
    Manifest manifest = new Manifest(); 
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); 
    JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest); 
    add(new File("inputDirectory"), target); 
    target.close(); 
} 

private void add(File source, JarOutputStream target) throws IOException 
{ 
    BufferedInputStream in = null; 
    try 
    { 
    if (source.isDirectory()) 
    { 
     String name = source.getPath().replace("\\", "/"); 
     if (!name.isEmpty()) 
     { 
     if (!name.endsWith("/")) 
      name += "/"; 
     JarEntry entry = new JarEntry(name); 
     entry.setTime(source.lastModified()); 
    target.putNextEntry(entry); 
    target.closeEntry(); 
    } 
    for (File nestedFile: source.listFiles()) 
    add(nestedFile, target); 
    return; 
} 

JarEntry entry = new JarEntry(source.getPath().replace("\\", "/")); 
entry.setTime(source.lastModified()); 
target.putNextEntry(entry); 
in = new BufferedInputStream(new FileInputStream(source)); 

byte[] buffer = new byte[1024]; 
while (true) 
{ 
    int count = in.read(buffer); 
    if (count == -1) 
    break; 
    target.write(buffer, 0, count); 
} 
target.closeEntry(); 
} 
finally 
    { 
    if (in != null) 
     in.close(); 
    } 
} 

比方說,我的目錄結構是

- C:/source 
-- C:/source/test.txt 
--- C:/source/folder/test2.txt 
----C:/source/folder/deeper/test3.txt 

我希望我的JAR進行結構如下

- META-INF/manifest.MF (I've already got this part sorted) 
-- test.txt 
--- folder (which then contains test2 and a sub folder called deeper which in turn contains test3.txt) 

我掙扎着爬遞歸權。

上面的代碼示例在我的zip中創建C:\source文件夾,這顯然不是我想要的。

回答

0

爲路徑條目使用相對路徑。該行應該是這樣的:

JarEntry entry = new JarEntry(source.getPath().substring(yourRootPath.length()).replace("\\", "/"); 

其中yourRootPath是的路徑是onle水平高於被包含所有內容的目錄(例如,您的遞歸的開始)。

在你的例子中,這將是「C:\」

+0

這部分工作。我實際上已將我的文件放在我的文檔(C:\ Users \ ian \ Documents \ source)中,並將您的路徑設置爲「C:\ Users \ ian \ Documents \」,現在獲取整個用戶 - > Ian - >放置在jar中的文檔也是如此。 –

+0

你是否在「新JarEntry(...)」的發生中改變了它? – masinger