. properties File

Source: Internet
Author: User
Tags list of attributes

When we write the program, some of the parameters are often changed, and this change is not what we foresee. For example, we developed a module to operate the database, in the development of our connection to the local database so IP, database name, table name, database host and other information is our local, to make this operation of the data module has universality, then the above information can not be written dead in the program. Usually our approach is to use a configuration file to solve the problem.

Various languages have their own profile types that are supported. Like Python, he supports the. ini file. Because he has an internal configparser class to support the reading and writing of the. ini file, the method provided by this class allows programmers to operate the. ini file freely. In Java, Java supports the reading and writing of. Properties files. The JDK built-in Java.util.Properties class facilitates our operation of the. Properties file.

I. . properties file Form ==========================================================

# The following is server, database information

Dbport = localhost

DatabaseName = MyDB

Dbusername = root

Dbpassword = root

# The following is the database table information

DBTable = MyTable

# The following is server information

IP = 192.168.0.9

In the above file we assume that the file name is: Test.properties file. Where # begins a behavior annotation information, which we call the key on the left side of the equal sign "=" and what we call value on the right side of the equal sign "=". (In fact, we often say that key-value pairs) key should be the variables in our program. And value is based on the actual situation we configure.

two. The Properties class properties in JDK exist in cell Java.util, which inherits from Hashtable and provides several main methods:
1. GetProperty (String key) to search for properties in this property list with the specified key. That is, the value of the key is obtained by the key of the parameter.

2. Load (InputStream instream), which reads the list of attributes (key and element pairs) from the input stream. Gets all key-value pairs in the file by loading the specified file, such as the Test.properties file above. To search for getproperty(String key).
3. SetProperty (String key,string value), call the Hashtable method put. He sets the value key-value pair by calling the base class's put method.

4. Store (OutputStream out,string comments) to write the list of properties in this properties table (key and element pairs) to the output stream in a format suitable for loading into the properties table using the Load method. In contrast to the load method, this 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.

With these several methods, we can operate on the. Properties file.

three. Code Instances

Package configuration;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.Properties;
/**
* Read Properties file
* @author Qutr
*
*/
public class Configuration
{
Private Properties Propertie;
Private FileInputStream Inputfile;
Private FileOutputStream outputfile;
/**
* Initialize Configuration Class
*/
Public Configuration ()
{
Propertie = new Properties ();
}
/**
* Initialize Configuration Class
* @param filePath the path + name of the configuration file to read
*/
Public Configuration (String FilePath)
{
Propertie = new Properties ();
try{
Inputfile = new FileInputStream (FilePath);
Propertie.load (Inputfile);
Inputfile.close ();
catch (FileNotFoundException ex) {
System.out.println ("Read Property file---> failed. -Cause: File path error or file not present ");
Ex.printstacktrace ();
catch (IOException ex) {
SYSTEM.OUT.PRINTLN ("Load file---> Fail!");
Ex.printstacktrace ();
}
}//end readconfiginfo (...)
/**
* Overloaded function, get the value of key
* @param key to get its value
* Value of @return key
*/
public string GetValue (string key)
{
if (Propertie.containskey (key)) {
String value = Propertie.getproperty (key);//Get the value of a property
return value;
}
Else
Return "";
}//end GetValue (...)
/**
* Overloaded function, get the value of key
* @param filename Properties file path + filename
* @param key to get its value
* Value of @return key
*/
public string GetValue (string fileName, String key)
{
try{
String value = "";
Inputfile = new FileInputStream (fileName);
Propertie.load (Inputfile);
Inputfile.close ();
if (Propertie.containskey (key)) {
Value = Propertie.getproperty (key);
return value;
}else
return value;
catch (FileNotFoundException e) {
E.printstacktrace ();
Return "";
catch (IOException e) {
E.printstacktrace ();
Return "";
catch (Exception ex) {
Ex.printstacktrace ();
Return "";
}
}//end GetValue (...)
/**
* Clear all keys and their values in the properties file
*/
public void Clear ()
{
Propertie.clear ();
}//end Clear ();
/**
* Change or add the value of a key, when the key exists in the properties file, the value of the key is replaced by value,
* When key does not exist, the value of the key is
* @param key to deposit
* @param value to be deposited
*/
public void SetValue (string key, String value)
{
Propertie.setproperty (key, value);
}//end SetValue (...)
/**
* The changed file data is deposited in the specified file, which may not exist in advance.
* @param filename File path + file name
* @param Description The description of the document
*/
public void SaveFile (string fileName, string description)
{
try{
outputfile = new FileOutputStream (fileName);
Propertie.store (outputfile, description);
Outputfile.close ();
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException IoE) {
Ioe.printstacktrace ();
}
}//end savefile (...)
public static void Main (string[] args)
{
Configuration rc = new Configuration (". \config\test.properties");//relative path
String IP = rc.getvalue ("IPP");//Read the value of the properties file below
String host = Rc.getvalue ("host");
String tab = rc.getvalue ("tab");
System.out.println ("IP =" + IP + "Ip-test leng =" + "Ip-test". Length ());//The following output properties read out values
System.out.println ("ip ' length =" + ip.length ());
SYSTEM.OUT.PRINTLN ("host =" + host);
SYSTEM.OUT.PRINTLN ("tab =" + TAB);
Configuration CF = new Configuration ();
String IPP = Cf.getvalue (". \config\test.properties", "IP");
System.out.println ("IPP =" + IPP);
Cf.clear ();
Cf.setvalue ("Min", "999");
Cf.setvalue ("Max", "1000");
Cf.savefile (". \config\save.perperties", "Test");
Configuration SAVECF = new Configuration ();
Savecf.setvalue ("Min", "10");
Savecf.setvalue ("Max", "1000");
Savecf.savefile (". \config\save.perperties");
}//end Main ()
}//end class Readconfiginfo

Four Summary it is not difficult to see from the example above that manipulating a configuration file in Java is very simple. In a module or system that requires a large amount of configuration information, it is necessary to encapsulate a specialized class for common use. With the final main function call, I believe you can see the use of the class. I hope we can show you a lot of advice.

Operation of Javaproperties files
The properties file in Java is a configuration file, mainly used to express configuration information, the file type is *.properties, the format is a text file, the file content is the format is "key = value" format, in the properties file, you can use "#" to make comments, The properties file is a lot of places to use in Java programming and is easy to operate. The following is an example of the operation of a Java properties file, with an operation method and a properties file. From which you can see how to read the properties file, and apply the values read out, is a good example of learning to manipulate the properties file.

A, properties file

Icisreport.properties
##################################################
# Industrial and Commercial report application icisreport configuration file #
# Author: Lei Zhimin #
# Date: November 21, 2006 #
###################################################
# Description: Business system TOPICIS and report system Icisreport is separate
# can be deployed separately to different servers, or deployed to the same service
# device; Icisreprot as a stand-alone Web application, you can use any
# The servlet container or the Java EE Server is deployed and run separately, or you can
# is applied as a library of the business system through the interface invocation of the business system. #
# icisreport IP
icisreport.server.ip=192.168.3.143
# Icisreport's Port
icisreport.server.port=8080
# Icisreport's Context Path
Icisreport.contextpath=/icisreport

------------------------------------------------------

Java method of manipulating properties files

Here is a way to manipulate the properties file
------------------------------------------------------
/**
* @return get the URL for icisreport report application
*/
Private String Geticisreporturl () {
String Icisreporturl = ""; URL for icisreport report application
String Icisreportserverip = ""; IP of the Icisreport server
String icisreportserverport = ""; Icisreport Server's service port
Stringicisreportcontextpath= ""; The ContextPath of Icisreport application

Properties prop = new properties ();
InputStream in;
try {
In =getclass (). getResourceAsStream ("/icisreport.properties");
Prop.load (in);
Set keyvalue= Prop.keyset ();
for (Iterator it = Keyvalue.iterator (); It.hasnext ();) {
String key = (string) it.next ();
if (Key.equals ("IcisReport.server.ip")) {
Icisreportserverip = (String) prop.get (key);
else if (key.equals ("IcisReport.server.port")) {
Icisreportserverport = (String) prop.get (key);
else if (key.equals ("Icisreport.contextpath")) {
Icisreportcontextpath= (String) prop.get (key);
}
}
catch (Exception e) {
Log.error ("io read error, icisreport.properties! not found");
}

        if (Icisreportserverip.trim (). Equals (")) {
            log.error (" Please check the value of the ICISREPORT.SERVER.IP entry in the profile icisreport.properties! ");
       }
        if (Icisreportserverport.trim (). Equals (")) {
            log.error (" Please check the value of the IcisReport.server.port entry in the profile icisreport.properties! ");
       }
        if (Icisreportserverport.trim (). Equals (")) {
            log.error (" Please check the value of the IcisReport.server.port entry in the profile icisreport.properties! ");
       }

       icisreporturl = "http://" + icisreportserverip.trim () + ":" + Icisreportserverport.trim () +icisreportcontextpath.trim ();
        Log.info ("acquired icisreporturl=" +icisreporturl);
        return icisreporturl;
   }
Summary: Java properties files need to be placed under classpath, so that the program can read, the classpath is actually Java class or library storage path, in Java Engineering, properties into a class file. In Web applications, the simplest way is to put it in the web-inf\classes directory of the Web application, or under Other folders, when you need to set the CLASSPATH environment variable, add this folder path to the CLASSPATH variable, This can also be read to. Here, you need to have a deep understanding of classpath, Classpath is not the system environment variables deliberately set,

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.