How to use Java property files?

后端 未结 17 1148
时光取名叫无心
时光取名叫无心 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:28

    You can load the property file suing the following way:

    InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
            Properties props =  new Properties();
            props.load(is);
    

    And then you can iterate over the map using a lambda expression like:

    props.stringPropertyNames().forEach(key -> {
                System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
            });
    
    0 讨论(0)
  • 2020-11-22 11:34

    If you put the properties file in the same package as class Foo, you can easily load it with

    new Properties().load(Foo.class.getResourceAsStream("file.properties"))
    

    Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.

    If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.

    0 讨论(0)
  • 2020-11-22 11:36

    In order:

    1. You can store the file pretty much anywhere.
    2. no extension is necessary.
    3. Montecristo has illustrated how to load this. That should work fine.
    4. propertyNames() gives you an enumeration to iterate through.
    0 讨论(0)
  • 2020-11-22 11:36

    Reading a properties file and loading its contents to Properties

    String filename = "sample.properties";
    Properties properties = new Properties();
    
    input = this.getClass().getClassLoader().getResourceAsStream(filename);
    properties.load(input);
    

    The following is the efficient way to iterate over a Properties

        for (Entry<Object, Object> entry : properties.entrySet()) {
    
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    
    0 讨论(0)
  • 2020-11-22 11:37

    In Java 8 to get all your properties

    public static Map<String, String> readPropertiesFile(String location) throws Exception {
    
        Map<String, String> properties = new HashMap<>();
    
        Properties props = new Properties();
        props.load(new FileInputStream(new File(location)));
    
        props.forEach((key, value) -> {
            properties.put(key.toString(), value.toString());
        });
    
        return properties;
    }
    
    0 讨论(0)
  • 2020-11-22 11:41

    Here is another way to iterate over the properties:

    Enumeration eProps = properties.propertyNames();
    while (eProps.hasMoreElements()) { 
        String key = (String) eProps.nextElement(); 
        String value = properties.getProperty(key); 
        System.out.println(key + " => " + value); 
    }
    
    0 讨论(0)
提交回复
热议问题