Common methods for reading and writing Properties properties files in java

  • 2020-05-30 20:07:12
  • OfStack

preface

You all know that Java has an important class called Properties ( Java.util.Properties ), which is mainly used to read the configuration files of Java. Various languages have their own configuration files that are supported. Many variables in the configuration files are often changed, which is also for the convenience of users, so that users can modify the relevant variable Settings without the program itself. The configuration file supported by Python is.ini. Similarly, it has its own ConfigParse class to read the configuration file, which is convenient for programmers or users to modify the.ini configuration file through the methods of this class. In Java, the configuration file is usually a.properties file in the form of a text file whose contents are in the "key = value" format, and the text annotation information can be annotated with "#".

It provides several main methods:

1. getProperty ( String key) , search the property list with the specified key. That is, value corresponding to key is obtained through the parameter key.

2. load ( InputStream inStream) , read the list of attributes (key and element pairs) from the input stream. Get all key-value pairs in a specified file by loading it, such as the test.properties file above. In order to offer getProperty ( String key) To search for.

3. setProperty ( String key, String value)  , calling the method put of Hashtable. He sets the key-value pair by calling the put method of the base class.

4. store ( OutputStream out, String comments) To fit the format loaded into the Properties table using the load method, write the list of attributes (key and element pairs) from the Properties table to the output stream. This method, in contrast to the load method, writes key-value pairs to the specified file.

5. clear () Clear all loaded key-value pairs. This method is provided in the base class.

The following sample code provides a set of common utility methods for reading and writing configuration files, which can be introduced according to your own project:


package com.javacui.lucene.jdbc;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertieUtil {
 private static Logger logger = Logger.getLogger(PropertieUtil.class);
 private PropertieUtil() {
 }
 /**
  *  Read a property from a configuration file 
  */
 public static String readValue(String filePath, String key) {
  Properties props = new Properties();
  try {
   //  Note the path to  /  Start, deal with nothing 
   if (!filePath.startsWith("/"))
    filePath = "/" + filePath;
   InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
   props.load(in);
   String value = props.getProperty(key);
   return value;
  } catch (Exception e) {
   logger.error(e);
   return null;
  }
 }
 /**
  *  Print the entire contents of the configuration file ( filePath , profile name, if there is a path, props/test.properties ) 
  */
 public static void readProperties(String filePath) {
  Properties props = new Properties();
  try {
   //  Note the path to  /  Start, deal with nothing 
   if (!filePath.startsWith("/"))
    filePath = "/" + filePath;
   InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
   props.load(in);
   Enumeration<?> en = props.propertyNames();
   //  Traverse the print 
   while (en.hasMoreElements()) {
    String key = (String) en.nextElement();
    String Property = props.getProperty(key);
    logger.info(key + ":" + Property);
   }
  } catch (Exception e) {
   logger.error(e);
  }
 }
 /**
  *  Writes the value to the configuration file 
  */
 public static void writeProperties(String fileName, String parameterName, String parameterValue) throws Exception {
  //  Local testing is especially important if it is maven Items, please \target View files in the directory, not under the source code 
  //  Note that the path cannot be added  /  If you add, you get rid of it 
  if (fileName.startsWith("/"))
   fileName.substring(1);
  String filePath = PropertieUtil.class.getResource("/").getPath()+fileName;
  //  Get configuration files 
  Properties pps = new Properties();
  InputStream in = new BufferedInputStream(new FileInputStream(filePath));
  pps.load(in);
  in.close();
  OutputStream out = new FileOutputStream(filePath);
  //  Sets the configuration name and value 
  pps.setProperty(parameterName, parameterValue);
  // comments  Equals the comment to the configuration file 
  pps.store(out, "Update " + parameterName + " name");
  out.flush();
  out.close();
 }
 public static void main(String[] args) throws Exception {
  readProperties("jdbc.properties");
//  logger.info(readValue("jdbc.properties", "JAVABLOG_WRITE_URL"));
//  writeProperties("test.properties", "test", "test");
 }
}

conclusion

The above is about java read and write Properties properties file public method all content, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: