简体   繁体   English

执行jar时相对路径不起作用

[英]relative path doesn't work when executing jar

i am developping an application where i have to specify the path of a file called dao.properties it works just fine but when i execute the jar using the cmd : java -jar StockManagement.jar i get the error that the file is not found (it works fine in netbeans) the class and the file are in the same folder. 我正在开发一个应用程序,其中我必须指定一个名为dao.properties的文件的路径,它的工作原理很好,但是当我使用cmd执行jar时:java -jar StockManagement.jar我收到找不到该文件的错误(它在netbeans中工作正常),该类和文件位于同一文件夹中。 i've tried a lot of relative paths and nothing works so this is my last hope here is the code and the hierarchy: 我已经尝试了很多相对路径,但没有任何效果,所以这是我最后的希望是代码和层次结构:

层次结构

码

thank y in advance 提前谢谢你

如果文件在代码库中,则应使用classLoader进行加载。

If I'm not mistaken, the way you're using ClassLoader is it looking for a file path relative to where it is being called. 如果我没有记错的话,那么您使用ClassLoader的方式就是寻找相对于被调用位置的文件路径。

From the picture, it seems that you're using ClassLoader from the DAOFactory class, is that right? 从图片看来,您似乎正在使用DAOFactory类中的ClassLoader,对吗? You're declaring the path to your file to be 您正在声明文件路径为

stock/DAO/dao.properties

If you're calling it from DAOFactory, Java looks for the file in 如果从DAOFactory调用它,则Java在以下位置查找文件:

<where DAOFactory is>/stock/DAO/dao.properties

If DAOFactory and dao.properties reside in the same file I think your file path should just be 如果DAOFactory和dao.properties驻留在同一文件中,我认为您的文件路径应为

dao.properties

So it looks in the same folder that DAOFactory is in. 因此,它看起来与DAOFactory所在的文件夹相同。

EDIT: Use DAOFactory class to read in properties file. 编辑:使用DAOFactory类读取属性文件。

Using something like the following code snippet, call this function from the DAOFactory class using just the main method to try to see if you can read the properties file without anything else. 使用类似于以下代码段的内容,仅使用main方法从DAOFactory类调用此函数,以尝试查看是否可以读取属性文件而无需其他任何操作。 Change any classes or names you need to to work on your local machine. 更改在本地计算机上工作所需的任何类或名称。

public static String getProperty(String property) {
  String value = "";

  try (InputStream is = DAOFactory.class.getResourceAsStream("dao.properties")) {
    Properties prop = new Properties();

    prop.load(is);
    value = prop.getProperty(property);
  } catch (Exception e) {
    e.printStackTrace();
  }

  return value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM