简体   繁体   中英

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. 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.

From the picture, it seems that you're using ClassLoader from the DAOFactory class, is that right? 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

<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

dao.properties

So it looks in the same folder that DAOFactory is in.

EDIT: Use DAOFactory class to read in properties file.

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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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