jar中图像和可执行文件的路径

时间:2014-07-21 20:52:44

标签: java eclipse jar path

我在eclipse中创建了一个java程序,现在我准备将它作为jar导出。我的程序使用图像文件和可执行文件。在eclipse中测试我的程序时,我用完整的路径引用了这些文件,我显然不能为jar做。因此,我改变了它们:

public static final String DRIVERLOC = "./resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());

File pic = new File("./images/Open16.gif");
openButton = new JButton("Select the Text File", createImageIcon(pic.getAbsolutePath()));

我将图像和资源和图像目录放在jar的同一目录中。现在出于某种原因,当我运行jar时,IEDriverServer工作正常,但图像不起作用,错误是它无法找到图像。我很困惑因为我似乎无法分辨出来。我还使用了“images / Open16.gif”,但也没用。为什么一个有效但另一个无效?解决这个问题的最简单方法是什么?

2 个答案:

答案 0 :(得分:1)

我们使用Selenium Drivers完成同样的事情。 你需要做的是将可执行文件从jar中取出并将其放在windows可以运行它的地方。如果您尝试在Windows资源管理器中打开jar / zip,然后双击jar / zip中的.exe,则windows会将该文件解压缩到临时目录,然后运行它。所以做同样的事情:

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TestClass {
    public static void main (String[] args) throws IOException {
        InputStream exeInputStream = TestClass.class.getClassLoader().getResourceAsStream("resources/IEDriverServer.exe");
        File tempFile = new File("./temp/IEDriverServer.exe");

        OutputStream exeOutputStream = new FileOutputStream(tempFile);
        IOUtils.copy(exeInputStream, exeOutputStream);

        // ./temp/IEDriverServer.exe will be a usable file now.
        System.setProperty("webdriver.ie.driver", tempFile.getAbsolutePath());
    }
}

让我们假设您保存jar并默认运行此主函数。 运行C:\code\> java -jar TestClass.jar将从C:\ code目录运行jar。它将在C:\ code \ temp \ IEDriverServer.exe

创建可执行文件

答案 1 :(得分:0)

将路径设置为“./resources/IEDriverServer.exe”,您指的是硬盘驱动器上的文件“。”哪个不存在。

您需要获取.jar文件的路径。 您可以使用

执行此操作
System.getProperty("java.class.path")

这可以返回多个值,由分号分隔。第一个应该是你的jar所在的文件夹。

您也可以使用

<AnyClass>.class.getProtectionDomain().getCodeSource().getLocation()

我希望这会有所帮助:)

编辑:

// First, retrieve the java.class.path property. It returns the location of all jars /  
// folders (the one that contains your jar and the location of all dependencies)
// In my test it returend a string with several locations split by a semi-colon, so we
// split it and only take the first argument
String jarLocation = System.getProperty("java.class.path").split(";")[0];

// Then we want to add that path to your ressource location
public static final String DRIVERLOC = jarLocation + "/resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());

您可以阅读 here