How to use Java property files?

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

    Properties has become legacy. Preferences class is preferred to Properties.

    A node in a hierarchical collection of preference data. This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.

    Unlike properties which are String based key-value pairs, The Preferences class has several methods used to get and put primitive data in the Preferences data store. We can use only the following types of data:

    1. String
    2. boolean
    3. double
    4. float
    5. int
    6. long
    7. byte array

    To load the the properties file, either you can provide absolute path Or use getResourceAsStream() if the properties file is present in your classpath.

    package com.mypack.test;
    
    import java.io.*;
    import java.util.*;
    import java.util.prefs.Preferences;
    
    public class PreferencesExample {
    
        public static void main(String args[]) throws FileNotFoundException {
            Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
            // Load file object
            File fileObj = new File("d:\\data.xml");
            try {
                FileInputStream fis = new FileInputStream(fileObj);
                ps.importPreferences(fis);
                System.out.println("Prefereces:"+ps);
                System.out.println("Get property1:"+ps.getInt("property1",10));
    
            } catch (Exception err) {
                err.printStackTrace();
            }
        }
    }
    

    xml file:

    
    
    
    
    
    
      
      
        
        
          
            
            
          
        
      
    
    
    
    

    Have a look at this article on internals of preferences store

提交回复
热议问题