Properties class uses Detailed

Java Properties class uses Detailed

 

Outline

Properties inherited from Hashtable. Represents a persistent set of properties, list of properties in the form of the key-value exists, key and value are strings.
Properties class is used by many Java classes. For example, when obtaining an environment variable as the value it returns System.getProperties () method.
We are many scenarios need to avoid hard-coding requires the use of properties file under the program to load configuration information needed, such as JDBC, MyBatis framework. Properties category is the middle of the bridge properties files and programs, whether read information from or write information to the properties file properties file should be via the Properties class.

A common method

Apart from the method as defined in Hashtable, Properties defines the following methods:

 

Properties class

From here we write, read, traverse perspectives to resolve common usage Properties class:

Write

Properties class calling the setProperty method of the key stored in memory, then read by the getProperty method, the propertyNames traverse method, but did not persist to the key-value pair property file, it needs to call the store method of key persistence the value of the properties file.

package cn.habitdiary;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import junit.framework.TestCase;

public class PropertiesTester extends TestCase {

    public void writeProperties() {
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream("config.properties");
            properties.setProperty("url", "jdbc:mysql://localhost:3306/");
            properties.setProperty("username", "root");
            properties.setProperty("password", "root");
            properties.setProperty("database", "users");//保存键值对到内存
            properties.store(output, "Steven1997 modify" + new Date().toString());
                        save the key to a file for//the catch
        } (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 

Read

Here are common ways to read six kinds of properties file:

package cn.habitdiary;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * 读取properties文件的方式
 *
 */
public class LoadPropertiesFileUtil {

    private static String basePath = "src/main/java/cn/habitdiary/prop.properties";
    private static String path = "";

    /**
     * 一、 使用java.util.Properties类的load(InputStream in)方法加载properties文件
     *
     * @return
     */
    public static String getPath1() {

        try {
            InputStream in = new BufferedInputStream(new FileInputStream(
                    new File(basePath)));
            Properties prop = new Properties();

            prop.load(in);

            path Prop.getProperty = ( "path" ); 

        } the catch (a FileNotFoundException E) { 
            System.out.println ( "Properties file path written in error, please check!" ); 
            E.printStackTrace (); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 

        return path; 
    } 

    / ** 
     * Second, the use getBundle java.util.ResourceBundle class () method 
     * Note: this parameter the getBundle () method can be written as the file name + properties package path, or the Throws 
     * 
     * @return 
     * / 
    public  static String getPath2 () { 
        ResourceBundle RB = ResourceBundle
                .getBundle("cn/habitdiary/prop");
        path = rb.getString("path");
        return path;
    }

    /**
     * 三、 使用java.util.PropertyResourceBundle类的构造函数
     *
     * @return
     */
    public static String getPath3() {
        InputStream in;
        try {
            in = new BufferedInputStream(new FileInputStream(basePath));
            ResourceBundle rb = new PropertyResourceBundle(in);
            path = rb.getString("path"); 
        } The catch (a FileNotFoundException E) {
             // the TODO Auto-Generated Block the catch 
            e.printStackTrace (); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 
        return path; 
    } 

    / ** 
     * The use of class variables of the getResourceAsStream () method 
     * Note: the getResourceAsStream parameter () method writes the format Properties package path + file name + extension. 
     * 
     * @return 
     * / 
    public  static String getPath4 () { 
        the InputStream in = LoadPropertiesFileUtil. class 
                .getResourceAsStream ("CN / habitdiary / prop.properties" ); 
        the Properties P = new new the Properties ();
         the try { 
            p.load (in); 
            path = p.getProperty ( "path" ); 
        } the catch (IOException E) { 
            e.printStackTrace ( ); 
        } 
        return path; 
    } 

    / ** 
     * V. 
     * use class.getClassLoader () is obtained java.lang.ClassLoader 
     () method of the getResourceAsStream * 
     * parameters getResourceAsStream (name) of the method must be a package path + file name + suffix 
     * otherwise it will report null pointer exception 
     * @return 
     * / 
    public  staticGetPath5 String () { 
        the InputStream in = LoadPropertiesFileUtil. Class .getClassLoader () 
                .getResourceAsStream ( "CN / habitdiary / prop.properties" ); 
        the Properties P = new new the Properties ();
         the try { 
            p.load (in); 
            path = P. getProperty ( "path" ); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 
        return path; 
    } 

    / ** 
     * 六、 使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
     * parameter format getSystemResourceAsStream () method is a fixed required 
     * 
     * @return
      * / 
    public  static String getPath6 () { 
        the InputStream in = ClassLoader 
                .getSystemResourceAsStream ( "CN / habitdiary / prop.properties" ); 
        the Properties P = new new the Properties ( );
         the try { 
            p.load (in); 
            path = p.getProperty ( "path" ); 
        } the catch (IOException E) {
             // the TODO Auto-Generated Block the catch 
            e.printStackTrace ();
        }
        return path;
    }

    public static void main(String[] args) {
        System.out.println(LoadPropertiesFileUtil.getPath1());
        System.out.println(LoadPropertiesFileUtil.getPath2());
        System.out.println(LoadPropertiesFileUtil.getPath3());
        System.out.println(LoadPropertiesFileUtil.getPath4());
        System.out.println(LoadPropertiesFileUtil.getPath5());
        System.out.println(LoadPropertiesFileUtil.getPath6());
    }
}

 

 

Wherein the first, four, five, six ways to obtain input stream file are then loaded into the method by Load Properties Properties object class (InputStream inStream), the final contents of the file operated by Properties object.
Second, the approach is to load the three files Properties ResourceBundle class, then the object to do gymnastics ResourceBundle properties file content.
The most important thing is when you load a file, the file path to the needs of each mode in accordance with the format defined method to load, otherwise it will throw various exceptions, such as null pointer exception.

Traversal

The following four kinds of methods to traverse all keys in the given Properties:

  / ** 
     * output properties of the key and value 
     * / 
    public  static  void printProp (the Properties properties) { 
        System.out.println ( "--------- (embodiment a) --------- --- " );
         for (String Key: properties.stringPropertyNames ()) { 
            System.out.println (Key +" = "+ Properties.getProperty (Key)); 
        } 

        System.out.println ( " ---- ----- (second approach) ----------------------- " ); 
        the set <Object> = properties.keySet Keys (); // returns the key attribute set 
        for (Object key: Keys) { 
            System.out.println (key.toString () + "=" +properties.get (Key)); 
        } 

        System.out.println ( "--------- (third approach) -----------------------" ); 
        the Set <of Map.Entry < Object, Object >> the entrySet = properties.entrySet ();
         // returns the key attributes of the entity 
        for (of Map.Entry <Object, Object> entry: the entrySet) { 
            System.out.println (entry.getKey () + " = "+ entry.getValue ()); 
        } 

        System.out.println ( " --------- (four ways) ----------------------- " ); 
        the Enumeration <?> = E properties.propertyNames ();
         the while (E.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = properties.getProperty(key);
            System.out.println(key + "=" + value);
        }
    }

 

Guess you like

Origin www.cnblogs.com/leeego-123/p/11535967.html