1
我在Java中生成一個.jar文件,但是.jar包含它在系統中的絕對路徑名(/ tmp/tempXXX/foo而不是/ foo)。 樹是這樣的:如何在Java中創建一個不包含絕對路徑名的Zip/Jar
.
|-- META-INF
|-|- ....
|-- tmp
|-|- tempXXX
|-|-|- foo
|-|-|- bar
取而代之的是:
.
|-- META-INF
|-|- ....
|-- foo
|-- bar
是否有可能解決這一問題?這是它的功能:
public static void add(File source, JarOutputStream target, String removeme)
throws IOException
{
BufferedInputStream in = null;
try
{
File source2 = source;
if (source.isDirectory())
{
String name = source2.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, removeme);
return;
}
JarEntry entry = new JarEntry(source2.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[2048];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
source2變量是修改路徑,但修改時,它給了一個「無效的.jar文件」錯誤。 修改是這樣的:
File source2 = new File(source.getPath().replaceAll("^" + removeme, ""));
編輯:它現在有效。這裏是新代碼,如果有人感興趣:
public static void add(File source, JarOutputStream target, String removeme)
throws IOException
{
BufferedInputStream in = null;
try
{
File parentDir = new File(removeme);
File source2 = new File(source.getCanonicalPath().substring(
parentDir.getCanonicalPath().length() + 1,
source.getCanonicalPath().length()));
if (source.isDirectory())
{
String name = source2.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, removeme);
return;
}
JarEntry entry = new JarEntry(source2.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[2048];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
非常感謝你,它的工作原理! – MiJyn 2012-02-15 19:15:07