Java Operation properties file, support for adding or updating multiple properties

Source: Internet
Author: User
Tags list of attributes

Java Operation properties file, support for new or updated multiple properties one, update or add a single property method
/** * Write Properties information * @param filePath absolute path (including file name and suffix name) * @param parametername name * @param parametervalue value */public static void WriteProperties (String filePath, String parametername, String parametervalue) {Propert       IES props = new Properties ();           try {//If the file does not exist, create a new file File=new file (FilePath);       if (!file.exists ()) {file.createnewfile ();           } InputStream fis = new FileInputStream (FilePath);           Reads the list of attributes (key and element pairs) from the input stream props.load (FIS);           Fis.close ();           OutputStream fos = new FileOutputStream (FilePath);           Props.setproperty (ParameterName, ParameterValue); In a format that is appropriate for loading into the properties table using the Load method,//Writes the attribute list (key and element pairs) in this properties table to the output stream Props.store (FOS, Parametern           AME); Fos.close (); Close stream} catch (IOException e) {System.err.println ("Visit" +filepath+ "for updating" +parametername+ "Value E       Rror "); }   }


Ii. methods for updating or adding n attributes
/** * @Title: Writemultiproperty * @Description: TODO (Modify multiple properties of properties file) * @param filePath Property file path (absolute path) * @param lis   t a column value to update or add * @return void */public static void Writemultiproperty (String filePath, list<pobj> List) {      if (list = = NULL | | list.size () = = 0) return;       Properties Props = new properties ();           try {//If the file does not exist, create a new file File=new file (FilePath);       if (!file.exists ()) {file.createnewfile ();           } InputStream fis = new FileInputStream (FilePath);           Reads the list of attributes (key and element pairs) from the input stream props.load (FIS);           Fis.close ();                      OutputStream fos = new FileOutputStream (FilePath);           Set properties for (Pobj obj:list) {Props.setproperty (Obj.getkey (), Obj.getvalue ());                      }//Save to attribute file Props.store (FOS, "Update Properties"); Fos.close (); Close stream} catch (IOException e) {System.err.println ("ViSit "+filepath+" for updating the PROPERTIES value error "); }   }

Updates or additions to multiple properties require a secondary class that temporarily stores the values that need to be manipulated

/**     * @ClassName: Pobj     * @Description: TODO (helper class, used to pass each property of a property file)     * @author Bruce [email protected]     * @ Date 2014-11-18 pm 11:31:00     */public    static class pobj{        private String key;    private String value;        Public Pobj () {}        /**     * <p>title: </p>     * <p>description: </p>     * @param key< c15/>* @param value     *    /Public Pobj (string key, String value) {    This.key = key;    This.value = value;    }    Public String GetKey () {return key;} public void Setkey (String key) {This.key = key;} Public String GetValue () {return value;} public void SetValue (String value) {this.value = value;}        }


Third, the method of reading the property file
Import Java.io.fileinputstream;import java.io.ioexception;import java.io.inputstream;import java.util.Properties; Import Org.apache.commons.io.ioutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class SETTINGSJNWJ {private static final Logger Logger = Loggerfactory.getlogger (settingsjnwj.class);p rivate static SETTINGSJNWJ instance;public Properties Settings = new Properties ();p ublic settingsjnwj () {String filename = ("d:/jnwj.pr Operties "); Logger.info ("Loading" + filename + "..."); InputStream stream = null;try {stream = new FileInputStream (filename); settings . Load (stream); Logger.info (filename + "loaded");} catch (IOException e) {logger.error ("Failed to" + filename, e);} finally {if (stream! = null) ioutils.closequietly (stream);}} Public synchronized static SETTINGSJNWJ getinstance () {if (instance = = null) {instance = new Settingsjnwj ();} return instance;} public string getString (string key) {return Settings.getproperty (key);} public static void Main (string[] args) {SETTINGSJNWJ s = settingsjnwj.getinstance (); System.out.println (S.settings.tostring ());//system.out.println (Settingsjnwj.getinstance (). getString ("uname"));}}

attached, properties file contents [Jnwj.properties]
uname=wckjupass=wckj123456unitcode=2340958039458

Iv. Testing
/** * @Title: Main * @Description: TODO (here is a word describing the function of this method) * @param @param args setting file * @return void return type * @throws */    public static void Main (string[] args) {//TODO auto-generated method stub//test1 ();    Test2 (); }/** * @Title: Multiple properties added or changed test */public static void Test2 () {list<pobj> List = new arraylist<    Pobj> ();    List.add (New Pobj ("uname", "wckj"));    List.add (New Pobj ("UPass", "wckj123456"));    List.add (New Pobj ("Unitcode", "2340958039458"));        Writemultiproperty ("d:/aiterw/conf/jnwj.properties", list);    System.out.println (Settingsjnwj.getinstance (). settings.tostring ()); }/** * @Title: New or changed test for single attribute */public static void Test1 () {//write file String passwork = "wckj1        23456 "; String JNWJ = Settings.getinstance (). getString ("JNWJ");          Here you can directly write your own property file location, such as: D:/jnwj.properties writeproperties (JNWJ, "UPass", passwork); Remove UserPassword from File, System.out.println (SETTINGSJNwj.getinstance (). getString ("UPass")); }


Reference: http://www.oschina.net/code/snippet_116183_12472#21008



Java Operation properties file, support for adding or updating multiple properties

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.