Read configuration files from different locations

  In development and test environments, it's easy to get confused about how to get configuration files in different locations. In order to avoid reinventing the wheel, record your own solution here:

  The following assumptions can be made:

    1. In the development environment, read the config.properties file under resources
    2. In the production environment, read the config.properties file in the same directory as the jar file, if there is no such config.properties file, read the jar package config.properties in

1  public  class ConfigUtils {
 2      /** 
3       * Get the configuration information content according to the content in the configuration file
 4       * @param property configured properties
 5       * @return configuration property value
 6       * @throws IOException
 7       */ 
8      public  static String getProperty( String property) throws IOException {
 9          Properties properties = new Properties();
 10          InputStream inputStream = null ;
 11          //Get the absolute path of the config.properties file in the same directory of the .jar file 
12          String configFilePath = System.getProperty("user.dir") + File.separator + "config.properties" ;
 13          // If the same as the .jar file level directory, the config.properties file exists, then use this file as the configuration file 
14          if ( new File(configFilePath).exists()) {
 15              inputStream = new BufferedInputStream( new FileInputStream(configFilePath));
 16          } else {
 17              / / If the config.properties file does not exist in the same directory as the .jar file, use the config.properties file in the .jar file as the configuration file 
18 inputStream              = ConfigUtils.class.getClassLoader().getResourceAsStream("config.properties");
19         }
20         properties.load(inputStream);
21         String value = properties.getProperty(property);
22         return value;
23     }
24 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691030&siteId=291194637