How to use Java property files?

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

    Here ready static class

    import java.io.*;
    import java.util.Properties;
    public class Settings {
        public static String Get(String name,String defVal){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                FileReader reader = new FileReader(configFile);
                Properties props = new Properties();
                props.load(reader);
                reader.close();
                return props.getProperty(name);
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
                return defVal;
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
                return defVal;
            } catch (Exception ex){
                logger.error(ex);
                return defVal;
            }
        }
        public static Integer Get(String name,Integer defVal){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                FileReader reader = new FileReader(configFile);
                Properties props = new Properties();
                props.load(reader);
                reader.close();
                return Integer.valueOf(props.getProperty(name));
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
                return defVal;
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
                return defVal;
            } catch (Exception ex){
                logger.error(ex);
                return defVal;
            }
        }
        public static Boolean Get(String name,Boolean defVal){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                FileReader reader = new FileReader(configFile);
                Properties props = new Properties();
                props.load(reader);
                reader.close();
                return Boolean.valueOf(props.getProperty(name));
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
                return defVal;
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
                return defVal;
            } catch (Exception ex){
                logger.error(ex);
                return defVal;
            }
        }
        public static void Set(String name, String value){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                Properties props = new Properties();
                FileReader reader = new FileReader(configFile);
                props.load(reader);
                props.setProperty(name, value.toString());
                FileWriter writer = new FileWriter(configFile);
                props.store(writer, Variables.SETTINGS_COMMENT);
                writer.close();
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
            } catch (Exception ex){
                logger.error(ex);
            }
        }
        public static void Set(String name, Integer value){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                Properties props = new Properties();
                FileReader reader = new FileReader(configFile);
                props.load(reader);
                props.setProperty(name, value.toString());
                FileWriter writer = new FileWriter(configFile);
                props.store(writer,Variables.SETTINGS_COMMENT);
                writer.close();
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
            } catch (Exception ex){
                logger.error(ex);
            }
        }
        public static void Set(String name, Boolean value){
            File configFile = new File(Variables.SETTINGS_FILE);
            try {
                Properties props = new Properties();
                FileReader reader = new FileReader(configFile);
                props.load(reader);
                props.setProperty(name, value.toString());
                FileWriter writer = new FileWriter(configFile);
                props.store(writer,Variables.SETTINGS_COMMENT);
                writer.close();
            } catch (FileNotFoundException ex) {
                // file does not exist
                logger.error(ex);
            } catch (IOException ex) {
                // I/O error
                logger.error(ex);
            } catch (Exception ex){
                logger.error(ex);
            }
        }
    }
    

    Here sample:

    Settings.Set("valueName1","value");
    String val1=Settings.Get("valueName1","value");
    Settings.Set("valueName2",true);
    Boolean val2=Settings.Get("valueName2",true);
    Settings.Set("valueName3",100);
    Integer val3=Settings.Get("valueName3",100);
    
    0 讨论(0)
  • 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:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
    <preferences EXTERNAL_XML_VERSION="1.0">
    <root type="user">
    <map />
    <node name="com">
      <map />
      <node name="mypack">
        <map />
        <node name="test">
          <map>
            <entry key="property1" value="80" />
            <entry key="property2" value="Red" />
          </map>
        </node>
      </node>
    </node>
    </root>
    </preferences>
    

    Have a look at this article on internals of preferences store

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

    You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.

    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream("path/filename"));
    } catch (IOException e) {
      ...
    }
    

    Iterate as:

    for(String key : properties.stringPropertyNames()) {
      String value = properties.getProperty(key);
      System.out.println(key + " => " + value);
    }
    
    0 讨论(0)
  • 2020-11-22 11:55
    • You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier.

    • Any extension is fine, although .properties is more common in my experience

    • Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)

    • Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

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

    By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:

    Properties props = new java.util.Properties();
    FileInputStream fis new FileInputStream("myfile.txt");
    props.load(fis)
    

    As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a FileInputStream.

    On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a ClassPathResource to load a property file using a package name from inside a JAR file.

    As for iterating through the properties, once the properties are loaded they are stored in the java.util.Properties object, which offer the propertyNames() method.

    0 讨论(0)
提交回复
热议问题