Executable jar won't find the properties files

后端 未结 5 1245
無奈伤痛
無奈伤痛 2020-12-09 17:18

I use this code in my program to load a properties file:

Properties properties = new Properties();
URL url = new App().getClass().getResource(PROPERTIES_FILE         


        
5条回答
  •  忘掉有多难
    2020-12-09 18:02

    There are two workarounds:

    1. Don't use the JAR as executabele JAR, but as library.

      java -cp .;filename.jar com.example.YourClassWithMain
      
    2. Obtain the root location of the JAR file and get the properties file from it.

      URL root = getClass().getProtectionDomain().getCodeSource().getLocation();
      URL propertiesFile = new URL(root, "filename.properties");
      Properties properties = new Properties();
      properties.load(propertiesFile.openStream());
      

    None of both are recommended approaches! The recommend approach is to have the following entry in JAR's /META-INF/MANIFEST.MF file:

    Class-Path: .
    

    Then it'll be available as classpath resource the usual way. You'll really have to instruct Maven somehow to generate the MANIFEST.MF file like that.

提交回复
热议问题