获取主可执行文件.jar文件的目录路径

时间:2014-05-19 04:34:59

标签: java

在调试中,我发现当前存储数据库文件(embedded derby database)的方式在运行由.jar编译的可执行NetBeans 8.0文件时不起作用。

简单地说,我需要一种方法让应用程序找到正在运行.jar文件的目录,并在同一目录中设置embedded DB database

如果它有帮助,我现在让它“工作”(在IDE中)的方式如下:

public final void setDBSystemDir() throws UnsupportedEncodingException, SQLException{
        String path = DataBase.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = URLDecoder.decode(path, "UTF-8");
        String systemDir = decodedPath + "/listData/";
        System.setProperty("derby.system.home", systemDir);
}

欢迎任何指示。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码获取路径

CodeSource source = DataBase.class.getProtectionDomain().getCodeSource();
File file = new File(source.getLocation().toURI().getPath());
String dir = file.getParentFile().getPath();
相关问题