簡體   English   中英

將文件夾寫入JAR文件

[英]Write folders to JAR File

我整個上午都在努力,但我無法弄清楚! 我基於此示例創建代碼

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文件夾,這顯然不是我想要的。

使用相對路徑作為路徑條目。 該行應如下所示:

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

其中yourRootPath是目錄的路徑,該路徑比要包含的所有內容(例如,遞歸的開始)高一個級別。

在您的示例中,這將是“ C:\\”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM