Operation of the properties class in Java

Source: Internet
Author: User

Knowledge without it is useless, and it has to be re-learned when it is really used. Recently looking at several open source simulator source code, which involves a lot about the properties of the reference, because Java has been a long time useless, and these simulators are mostly written in Java, plus some scripting language Python,perl, and so on, have to be picked up again. This article by looking at "Java programming thought" and some Netizen's blog summary, only for the simple introduction properties class related operation.

First, Java Properties class

Java has a relatively important class properties (Java.util.Properties), mainly used to read Java configuration files, various languages have their own supported configuration files, many variables in the configuration file is often changed, and this is also for the convenience of users, Allows the user to change the relevant variable settings from the program itself. Like a python-supported profile is an. ini file, it also has its own class configparse that reads the configuration file, allowing programmers or users to modify the. ini configuration file by means of this class. In Java, its configuration file is usually a. properties file, formatted as a text file, the format of the contents of the file is "key = value" format, the text annotation information can be used "#" to comment.

The properties class inherits from Hashtable, as follows:

It provides several main methods:

1. GetProperty (String key) that searches for properties in this property list with the specified key. That is, by the parameter key, the value corresponding to the key is obtained.

2. load (InputStream instream) to read the list of attributes (key and element pairs) from the input stream. Gets all the key-value pairs in the file by loading the specified file (for example, the Test.properties file above). To search for GetProperty (String key).

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

4. Store (OutputStream out, String comments) writes the list of attributes (key and element pairs) in this properties table to the output stream, in a format that is appropriate for loading into the properties table using the Load method. In contrast to the load method, the method writes a key-value pair to the specified file.

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

Second, Java read the properties file

There are many ways to read the properties file in Java, see: Six ways Java reads the properties file

But the most common is implemented by the Java.lang.Class class's getResourceAsStream (String name) method, which can be called as follows:

InputStream in = GetClass (). getResourceAsStream ("Resource Name"); As we write the program, use this one enough.

Or the following is commonly used:

InputStream in = new Bufferedinputstream (new FileInputStream (filepath));

Third, relevant examples

Here are a few examples to deepen the understanding and memory of the properties class.

We know that the Java Virtual Machine (JVM) has its own system configuration file (System.properties), which we can obtain in the following way.

1. Get the system properties of the JVM

Import java.util.Properties;  Public class READJVM {    publicstaticvoid  main (string[] args) {        =  System.getproperties ();        Pps.list (System.out);    }}

Results:

2. Create a new configuration file (test.properties)

name=jjweight=4444height=3333

 Public classgetProperties { Public Static voidMain (string[] args)throwsFileNotFoundException, IOException {Properties pps=NewProperties (); Pps.load (NewFileInputStream ("Test.properties")); Enumeration Enum1= Pps.propertynames ();//get the name of the configuration file         while(Enum1.hasmoreelements ()) {String strkey=(String) enum1.nextelement (); String strvalue=Pps.getproperty (strkey); System.out.println (strkey+ "=" +strvalue); }    }}

3, a more comprehensive example

Read value by key

Read all information about the properties

Write a new properties information

//about operations common to the Properties class Public classtestproperties {//read value by key     Public Staticstring Getvaluebykey (String FilePath, String key) {Properties pps=NewProperties (); Try{InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath));            Pps.load (in); String value=Pps.getproperty (key); SYSTEM.OUT.PRINTLN (Key+ " = " +value); returnvalue; }Catch(IOException e) {e.printstacktrace (); return NULL; }    }        //Read all information about the properties     Public Static voidGetallproperties (String FilePath)throwsIOException {Properties pps=NewProperties (); InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath));        Pps.load (in); Enumeration en= Pps.propertynames ();//get the name of the configuration file                 while(En.hasmoreelements ()) {String strkey=(String) en.nextelement (); String strvalue=Pps.getproperty (strkey); System.out.println (strkey+ "=" +strvalue); }            }        //Write properties Information     Public Static voidWriteProperties (String FilePath, String PKey, String pValue)throwsIOException {Properties pps=NewProperties (); InputStream in=NewFileInputStream (FilePath); //read the list of attributes from the input stream (key and element pairs)pps.load (in); //Call the Hashtable method put.          Use the GetProperty method to provide parallelism. //enforces the use of strings for the keys and values of the properties. The return value is the result of the Hashtable call put. OutputStream out =NewFileOutputStream (FilePath);        Pps.setproperty (PKey, PValue); //In a format that is appropriate for loading into the Properties table using the Load method,//writes the list of attributes (key and element pairs) in this properties table to the output streamPps.store (out, "Update" + PKey + "name")); }         Public Static voidMain (String [] args)throwsioexception{//String value = Getvaluebykey ("test.properties", "name"); //System.out.println (value); //getallproperties ("test.properties");WriteProperties ("Test.properties", "Long", "212"); }}

Results:
The data in the Test.properties file is:

#Update long Name#sun Feb 18:17:16 CST 2014name=jjweight=4444long=212height=3333

Operation of the properties class in Java

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.