java to read and write configuration files

Java Properties read and write configuration files
1.Properties class configuration file and Properties

Properties class inherits from Hashtable class and implements the Map interface, but also use a form of key-value pairs to save the property set. However Properties has a special place is its keys and values ​​are string types.

The main method 2.Properties

(1)load(InputStream inStream)

This method may correspond to the attribute from the file input stream .properties, load class object property list to the Properties. The following code:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("a.properties");
pro.load(in);
in.close();

(2)store(OutputStream out, String comments)

This method saves the list of attributes Properties class object to the output stream. The following code:


FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close();

If comments are not empty, save the file attributes first line is #comments, represents the comment information; if no comment is empty.

Annotation information is behind the current time save property file.

(3)getProperty/setProperty

These two methods are respectively get and set property information.

3. Code Example

A.properties properties file as follows:

= the root name
Pass = Liu
Key = value
read a.properties property list, and the attribute file b.properties generated. code show as below:

import java.io.BufferedInputStream;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.InputStream; 
  import java.util.Iterator;
  import java.util.Properties; 
  
  public class PropertyTest {
      public static void main(String[] args) { 
         Properties prop = new Properties();     
         try{
            //读取属性文件a.properties
            InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
            prop.load(in);     ///加载属性列表
             Iterator<String> it=prop.stringPropertyNames().iterator();
            while(it.hasNext()){
               String key=it.next();
                System.out.println(key+":"+prop.getProperty(key));
            }
            in.close();
           
          ///保存属性到b.properties文件
      FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打开
          prop.setProperty("phone", "10086");
            prop.store(oFile, "The New properties file");
            oFile.close();
        }
       catch(Exception e){
            System.out.println(e);
         }
     } 
}
Published 32 original articles · won praise 21 · views 8476

Guess you like

Origin blog.csdn.net/weixin_39638459/article/details/87973353