How to use Java property files?

后端 未结 17 1507
时光取名叫无心
时光取名叫无心 2020-11-22 11:13

I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.

Questions:

  • Do I ne
17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 11:42

    1) It is good to have your property file in classpath but you can place it anywhere in project.

    Below is how you load property file from classpath and read all properties.

    Properties prop = new Properties();
    InputStream input = null;
    
    try {
    
        String filename = "path to property file";
        input = getClass().getClassLoader().getResourceAsStream(filename);
        if (input == null) {
            System.out.println("Sorry, unable to find " + filename);
            return;
        }
    
        prop.load(input);
    
        Enumeration e = prop.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = prop.getProperty(key);
            System.out.println("Key : " + key + ", Value : " + value);
        }
    
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    2) Property files have the extension as .properties

提交回复
热议问题