Encapsulate the configuration file in Java (1)-use properties

Source: Internet
Author: User

Whether there is a graphical option configuration dialog box or a Registry provided by the system, local configuration files in the text form are still the most secure and widely used configuration information storage form. The general mode of configuration information is that a configuration item corresponds to a value. The former is generally a string, and the latter may be a number, a string, or something else. In traditional Win32 programming, there are system-provided APIs for our interpretation. the INI file also comes with an encapsulated API for operating the registry. net is interpreted in XML format. config file. In Java, encapsulation of configuration files is also very meaningful.

Encapsulation should achieve the following effect: the application only reads the value by name, sets the value, and saves the configuration information, without worrying about the specific file format and resolution. File Format (plain text? XML? Database ?) , Io method (local file? Remote File? Console stream ?) Changes within the encapsulation class do not affect the application's perception of configuration information.

From the correspondence between key names and values and the access to files, we are most likely to think of Java. util. properties object, which is a subclass of hashtable and stores the two original groups corresponding to key names and values of many groups, it also provides fast query and direct reading and saving of files. For more information, see the relevant documentation.

First, you can customize an exception:


// Configurationexception. Java
Package configuration;

Public class configurationexception extends exception {
Public configurationexception (){}
Public configurationexception (string MSG ){
Super (MSG );
}
}

Then our encapsulation class:


// Configuration. Java
Package configuration;
Import java. Io .*;
Import java. util .*;
Import configuration .*;

Public class configuration {
Private Properties Config = new properties (); // record configuration items
Private string fn = NULL; // record the configuration file name

// This constructor is used to create a configuration file.
Public configuration (){}

// Read configuration information from the specified file name
Public configuration (string filename)
Throws configurationexception {
Try {
Fileinputstream fin = new fileinputstream (filename );
Config. Load (FIN); // load the file
Fin. Close ();
}
Catch (ioexception ex ){
Throw new configurationexception
("The specified configuration file cannot be read:" + filename );
}
Fn = filename;
}

// Specify the configuration item name and return the configuration value
Public String getvalue (string itemname ){
Return config. getproperty (itemname );
}

// Specify the configuration item name and default value, and return the configuration value
Public String getvalue (string itemname,
String defaultvalue ){
Return config. getproperty (itemname, defaultvalue );
}

// Set the configuration item name and its value
Public void setvalue (string itemname, string value ){
Config. setproperty (itemname, value );
Return;
}

// Save the configuration file and specify the file name and header description
Public void SaveFile (string filename, string description)
Throws configurationexception {
Try {
Fileoutputstream fout
= New fileoutputstream (filename );
Config. Store (fout, description); // save the file
Fout. Close ();
}
Catch (ioexception ex ){
Throw new configurationexception
("The specified configuration file cannot be saved:" + filename );
}
}

// Save the configuration file and specify the file name
Public void SaveFile (string filename)
Throws configurationexception {
SaveFile (filename ,"");
}

// Save the configuration file with the original file name
Public void SaveFile () throws configurationexception {
If (fn. Length () = 0)
Throw new configurationexception
("The name of the configuration file to be saved must be specified ");
SaveFile (FN );
}
}

From this encapsulation class, we can see that when instantiating an object, we can specify a file name to read configuration information from it, get the property value through the getvalue method, set the property value by the setvalue method, and save the file by the SaveFile method. Then let's take a look at how to use it:


// Setconfig. Java
Import configuration. *; // contains this package before you can use the configuration class.
Import java. Io .*;

Public class setconfig {
Public static void main (string [] ARGs ){
Try {
Configuration Config = new configuration ();
// Set some attribute values
Config. setvalue ("max_users_count", "50 ");
Config. setvalue ("max_openedfile_count", "20 ");
// Save the file
Config. SaveFile ("system. conf ",
"Sytem global configuration ");
}
Catch (configurationexception ex ){
// Capture custom exceptions
Ex. printstacktrace ();
}
}
}

This program creates a new configuration and sets two configuration items: max_users_count to 50; max_openedfile_count to 20. Finally, save the configuration as the system. conf file and add the header comment "sytem global configuration ". After execution, a system. conf file is generated in the directory where the program is located. Open it in a text editor to see what the content is:


# Sytem global configuration
# Mon Aug 02 23:43:39 PDT 2004.
Max_openedfile_count = 20
Max_users_count = 50

We can see that the first line is written with the header comment we added, and the second line automatically generates a time, the configuration information is recorded in the form of <configuration item name >=< configuration value>. Here we will read this configuration file:


// Readconfig. Java
Import configuration .*;

Public class readconfig {
Public static void main (string [] ARGs ){
Try {
// Read the specified file
Configuration config
= New configuration ("system. conf ");
// Obtain a specific value
System. Out. println
(Config. getvalue ("max_users_count") +
"Users can be actived at the same time ");
// Specify the default value
System. Out. println
(Config. getvalue ("max_openedfile_count", "10") +
"Files can be opened at the same time ");
}
Catch (configurationexception ex ){
Ex. printstacktrace ();
}
}
}

System output


50 users can be actived at the same time
20 files can be opened at the same time

Such information. Indicates that the configuration information is successfully read.

In this way, our encapsulation class can perform common configuration information operations. In most cases, this class is enough. The code here is reusable. You can directly copy it to your project. Note: These attribute values can be modified in the file by yourself, which is also the most common usage method in the configuration file. The values starting with # indicate annotations and can be added or deleted at will.

The task is completed, but not perfect. The most convenient use of properties is the existing query, setting, and file access methods. However, such <configuration item name >=< configuration value> format is only convenient for Java, considering the future scalability of the system or the migration of the development platform, it is not appropriate. Next, we will try to use Dom to encapsulate configuration files in XML format.

 

Related Article

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.