【发布时间】:2014-03-10 17:52:18
【问题描述】:
我正在尝试以编程方式创建一个可运行的 jar 文件。我正在使用以下代码:
添加方法:
private static void add(File source, JarOutputStream target) throws IOException
{
BufferedInputStream in = null;
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", File.separator);
if (!name.isEmpty())
{
if (!name.endsWith(File.separator))
name += File.separator;
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();
}
}
它的实现:
try {
File[] files = new File("tmp").listFiles();
for (File file : files) {
System.out.println("Archiving: "+file.getName());
add(file, target);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
target.close();
} catch (IOException e) {
e.printStackTrace();
}
我正在尝试将 tmp 目录的所有内容添加到我的 jar 中,但我不想为所有命名空间添加前缀 tmp.。我尝试使用此代码遍历 tmp 中的文件并添加它们,但我不断收到错误消息“没有这样的文件或目录”。我很确定这是因为它在 tmp 目录之外查找。但是,当我将其更改为 add(new File("tmp"+File.separator+file.getName()), target); 时,我的命名空间中最终会出现“tmp”(因为我从 tmp/ 目录开始)。有没有办法解决这个问题?
这是一个例子:
我有一个带有Main-Class 属性com.name.proj.ProjDriver 的jar 文件
当我将它解压缩到 tmp 文件夹中时,我最终得到了 tmp/com/name/proj/ProjDriver.class 中的文件。然后我使用旧 jar 中的清单对象重新压缩我的 jar,仍然将主类指定为 com.name.proj.ProjDriver,但现在它实际上是 tmp.com.name.proj.ProjDriver。如何避免将 tmp. 作为所有命名空间的前缀?
【问题讨论】:
-
这将不起作用,因为每个类顶部的包语句将是错误的。此外,其他类将无法引用它们。
-
原谅我。我尝试了另一个答案,在我的电脑上它可以工作,希望它可以帮助你到达你想要的地方。
标签: java jar namespaces archive executable-jar