Home >Java >javaTutorial >Detailed explanation of java code for operating Properties

Detailed explanation of java code for operating Properties

Y2J
Y2JOriginal
2017-05-16 09:52:571334browse

This article mainly introduces the detailed explanation of Java operation Properties configuration file, and introduces Properties and main methods in detail. If you are interested, you can learn more

1 Introduction:

The java.util.Properties class provided by JDK inherits from the Hashtable class and implements the Map interface. It uses a key-value pair to save the property set, where the key and value are both string types.

The java.util.Properties class provides getProperty() and setProperty() methods to operate property files, while using the load() method and store() method to load and save the Properties configuration file.

The java.util.ResourceBundle class also provides methods for reading the Properties configuration file. ResourceBundle is an abstract class.

2. Main methods in Properties

1) load(InputStream inStream): This method can load properties from the file corresponding to the .properties property file into the stream. List to Properties class object . There are two methods of loadOverload: load(InputStream inStream), load(Reader reader), which can load property files in different ways.

InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("demo.properties"); 
//通过当前类加载器的getResourceAsStream方法获取
//TestProperties当前类名;TestProperties.class.取得当前对象所属的Class对象; getClassLoader():取得该Class对象的类装载器

InputStream in = ClassLoader.getSystemResourceAsStream("filePath");

InputStream inStream = new FileInputStream(new File("filePath")); //从文件获取
InputStream in = context.getResourceAsStream("filePath");     //在servlet中,可以通过context来获取InputStream
InputStream inStream = new URL("path").openStream();            //通过URL来获取

The reading method is as follows:

Properties pro = new Properties();                   //实例化一个Properties对象
InputStream inStream = new FileInputStream("demo.properties");     //获取属性文件的文件输入流
pro.load(nStream);
inStream.close();

2)store(OutputStream out,String comments): This method writes the property list of the Properties class object into the .properties configuration file. As follows:

FileOutputStream outStream = new FileOutputStream("demo.properties");
pro.store(outStream,"Comment");
outStream.close();

3 The main methods in ResourceBundle

are obtained through the ResourceBundle.getBundle()static method. This method obtains the properties attribute file. There is no need to add the .properties suffix. ResourceBundle objects can also be obtained from InputStream.

ResourceBundle resource = ResourceBundle.getBundle("com/xiang/demo");//emo为属性文件名,放在包com.xiang下,如果是放在src下,直接用test即可 
ResourceBundle resource1 = new PropertyResourceBundle(inStream);  
String value = resource.getString("name");

The problem encountered during use may be the path of the configuration file. When the configuration file is not under the package where the current class is located, you need to use the package name qualification; if the attribute file is under the src root directory, directly Just use demo.properties or demo.

4 Properties operation example

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * Java中Preperties配置文件工具类
 * @author shu
 *
 */
public class PropsUtil {
  private String path = "";
  private Properties properties ;
  
  /**
   * 默认构造函数
   */
  public PropsUtil() {}
  
  /**
   * 构造函数
   * @param path 传入Properties地址值
   */
  public PropsUtil(String path) {
    this.path = path;
  }
  
  /**
   * 加载properties文件
   * @return 返回读取到的properties对象
   */
  public Properties loadProps(){
    InputStream inStream = ClassLoader.getSystemResourceAsStream(path);    
    try {
      if(inStream==null)
        throw new FileNotFoundException(path + " file is not found");
      properties = new Properties();
      properties.load(inStream);
      inStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return properties;
  }
  
  /**
   * 将配置写入到文件
   */
  public void writeFile(){
    // 获取文件输出流
    try {
      FileOutputStream outputStream = new FileOutputStream( new File(ClassLoader.getSystemResource(path).toURI()));
      properties.store(outputStream, null);
      outputStream.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  /**
   * 通过关键字获取值
   * @param key
   * @return 返回对应的字符串,如果无,返回null
   */
  public String getValueByKey(String key) {
    if(properties==null)
      properties = loadProps();
    String val = properties.getProperty(key.trim());
    return val;
  }
  
  /**
   * 通过关键字获取值
   * @param key 需要获取的关键字
   * @param defaultValue 若找不到对应的关键字时返回的值
   * @return 返回找到的字符串
   */
  public String getValueByKey(String key,String defaultValue){
    if(properties==null)
      properties = loadProps();
    return properties.getProperty(key, defaultValue);
  }
  
  /**
   * 获取Properties所有的值
   * @return 返回Properties的键值对
   */
  public Map<String, String> getAllProperties() {
    if(properties==null)
      properties = loadProps();
    Map<String, String> map = new HashMap<String, String>();
    // 获取所有的键值
    Iterator<String> it=properties.stringPropertyNames().iterator();
    while(it.hasNext()){
      String key=it.next();
      map.put(key, properties.getProperty(key));
    }
    /*Enumeration enumeration = properties.propertyNames();
    while (enumeration.hasMoreElements()) {
      String key = (String) enumeration.nextElement();
      String value = getValueByKey(key);
      map.put(key, value);
    }*/
    return map;
  }

  /**
   * 往Properties写入新的键值且保存
   * @param key 对应的键
   * @param value 对应的值
   */
  public void addProperties(String key, String value) {
    if(properties==null)
      properties = loadProps();
    properties.setProperty(key, value);
    try {
      writeFile();
    } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
  }
  
  /**
   * 更新配置文件
   * @param key 对应的键
   * @param value 对应的值
   */
   public void update(String key,String value){
     if(properties==null)
      properties = loadProps();
     if(properties.containsKey(key))
       properties.replace(key, value);
    try {
      writeFile();
    } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
   }
   
   /**
   * 刪除某一鍵值对
   * @param key
   */
   public void deleteByKey(String key){
     if(properties==null)
      properties = loadProps();
     if(!properties.containsKey(key))
       throw new RuntimeException("not such key");
     properties.remove(key);
     try {
      writeFile();
     } catch (Exception e) {
      throw new RuntimeException("write fail");
    }
   }
   
   /**
   * 设置path值
   * @param path
   */
   public void setPath(String path){
     this.path = path;
   }
}

[Related recommendations]

1. Special recommendations: "php Programmer Toolbox" V0.1 version download

2. Java Free Video Tutorial

3. JAVA Tutorial Manual

The above is the detailed content of Detailed explanation of java code for operating Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn