Java reads the properties file [Post]

Source: Internet
Author: User
Read the properties file in Java]

Use j2se API to read properties files

1. Use the load () method of Java. util. properties class
Example: inputstream in = lnew bufferedinputstream (New fileinputstream (name ));
Properties P = new properties ();
P. Load (in );

2. Use the getbundle () method of the Java. util. resourcebundle class
Example: resourcebundle RB = resourcebundle. getbundle (name, locale. getdefault ());

3. Use the constructor of the Java. util. propertyresourcebundle class
Example: inputstream in = new bufferedinputstream (New fileinputstream (name ));
Resourcebundle RB = new propertyresourcebundle (in );

4. Use the getresourceasstream () method of the class variable
Example: inputstream in = jproperties. Class. getresourceasstream (name );
Properties P = new properties ();
P. Load (in );

5. Getresourceasstream () method of Java. Lang. classloader obtained by using class. getclassloader ()
Example: inputstream in = jproperties. Class. getclassloader (). getresourceasstream (name );
Properties P = new properties ();
P. Load (in );

6. Use the getsystemresourceasstream () Static Method of the Java. Lang. classloader class
Example: inputstream in = classloader. getsystemresourceasstream (name );
Properties P = new properties ();
P. Load (in );

Supplement

You can use the getresourceasstream () method of javax. servlet. servletcontext in servlet.
Example: inputstream in = context. getresourceasstream (PATH );
Properties P = new properties ();
P. Load (in );

For a complete example, refer to the attachment file.
For details about how to upload files, see the following. I had to paste all the source files.
Jproperties. Java File

Package com. kindani;

// Import javax. servlet. servletcontext;
Import java. util .*;
Import java. Io. inputstream;
Import java. Io. ioexception;
Import java. Io. bufferedinputstream;
Import java. Io. fileinputstream;

Public class jproperties {

Public final static int by_properties = 1;
Public final static int by_resourcebundle = 2;
Public final static int by_propertyresourcebundle = 3;
Public final static int by_class = 4;
Public final static int by_classloader = 5;
Public final static int by_system_classloader = 6;

Public Final Static Properties loadproperties (final string name, final int type) throws ioexception {
Properties P = new properties ();
Inputstream in = NULL;
If (type = by_properties ){
In = new bufferedinputstream (New fileinputstream (name ));
Assert (in! = NULL );
P. Load (in );
} Else if (type = by_resourcebundle ){
Resourcebundle RB = resourcebundle. getbundle (name, locale. getdefault ());
Assert (rb! = NULL );
P = new resourcebundleadapter (RB );
} Else if (type = by_propertyresourcebundle ){
In = new bufferedinputstream (New fileinputstream (name ));
Assert (in! = NULL );
Resourcebundle RB = new propertyresourcebundle (in );
P = new resourcebundleadapter (RB );
} Else if (type = by_class ){
Assert (jproperties. Class. Equals (New jproperties (). getclass ()));
In = jproperties. Class. getresourceasstream (name );
Assert (in! = NULL );
P. Load (in );
// Return New jproperties (). getclass (). getresourceasstream (name );
} Else if (type = by_classloader ){
Assert (jproperties. Class. getclassloader (). Equals (New jproperties (). getclass (). getclassloader ()));
In = jproperties. Class. getclassloader (). getresourceasstream (name );
Assert (in! = NULL );
P. Load (in );
// Return New jproperties (). getclass (). getclassloader (). getresourceasstream (name );
} Else if (type = by_system_classloader ){
In = classloader. getsystemresourceasstream (name );
Assert (in! = NULL );
P. Load (in );
}

If (in! = NULL ){
In. Close ();
}
Return P;

}

// ------------------------------------------------ Servlet used

// ------------------------------------------------ Support Class

Public static class resourcebundleadapter extends properties {
Public resourcebundleadapter (resourcebundle Rb ){
Assert (rb instanceof java. util. propertyresourcebundle );
This. RB = RB;
Java. util. Enumeration E = RB. getkeys ();
While (E. hasmoreelements ()){
Object o = E. nextelement ();
This. Put (O, RB. GetObject (string) O ));
}
}

Private resourcebundle RB = NULL;

Public resourcebundle getbundle (string basename ){
Return resourcebundle. getbundle (basename );
}

Public resourcebundle getbundle (string basename, locale ){
Return resourcebundle. getbundle (basename, locale );
}

Public resourcebundle getbundle (string basename, locale, classloader loader ){
Return resourcebundle. getbundle (basename, locale, loader );
}

Public enumeration getkeys (){
Return RB. getkeys ();
}

Public locale getlocale (){
Return RB. getlocale ();
}

Public object GetObject (string key ){
Return RB. GetObject (key );
}

Public String getstring (string key ){
Return RB. getstring (key );
}

Public String [] getstringarray (string key ){
Return RB. getstringarray (key );
}

Protected object handlegetobject (string key ){
Return (propertyresourcebundle) Rb). handlegetobject (key );
}

}

}

Jpropertiestest. Java File

Package com. kindani. test;

Import JUnit. Framework .*;
Import com. kindani. jproperties;

// Import javax. servlet. servletcontext;
Import java. util. properties;

Public class jpropertiestest extends testcase {
Jproperties;
String key = "helloworld. Title ";
String value = "Hello world! ";

Public void testloadproperties () throws exception {
String name = NULL;
Properties P = new properties ();

Name = "C: // ideap // properties4methods // SRC // com // kindani // test // localstrings. properties ";
P = jproperties. loadproperties (name, jproperties. by_properties );
Assertequals (value, P. getproperty (key ));

Name = "com. kindani. Test. localstrings ";
P = jproperties. loadproperties (name, jproperties. by_resourcebundle );
Assertequals (value, P. getproperty (key ));
Assertequals (value, (jproperties. resourcebundleadapter) P). getstring (key ));

Name = "C: // ideap // properties4methods // SRC // com // kindani // test // localstrings. properties ";
P = jproperties. loadproperties (name, jproperties. by_propertyresourcebundle );
Assertequals (value, P. getproperty (key ));
Assertequals (value, (jproperties. resourcebundleadapter) P). getstring (key ));

Name = "// com // kindani // test // localstrings. properties ";
P = jproperties. loadproperties (name, jproperties. by_system_classloader );
Assertequals (value, P. getproperty (key ));

Name = "// com // kindani // test // localstrings. properties ";
P = jproperties. loadproperties (name, jproperties. by_classloader );
Assertequals (value, P. getproperty (key ));

Name = "test // localstrings. properties ";
P = jproperties. loadproperties (name, jproperties. by_class );
Assertequals (value, P. getproperty (key ));
}

}

The properties file is in the same directory as the jpropertiestest. Java file.
Localstrings. properties File
# $ ID: localstrings. properties, v 1.1 2000/08/17 00:57:52 horwat exp $

# Default localized resources for example servlets
# This locale is en_us

Helloworld. Title = Hello world!

Requestinfo. Title = request information example
Requestinfo. Label. method = method:
Requestinfo. Label. requesturi = request URI:
Requestinfo. Label. Protocol = protocol:
Requestinfo. Label. pathinfo = Path Info:
Requestinfo. Label. remoteaddr = remote address:

Requestheader. Title = request header example

Requestparams. Title = Request Parameters example
Requestparams. Params-in-req = parameters in this request:
Requestparams. No-Params = no parameters, please enter some
Requestparams. firstname = First name:
Requestparams. lastname = Last Name:

Cookies. Title = cookies example
Cookies. Cookies = your browser is sending the following cookies:
Cookies. No-Cookies = your browser isn' t sending any cookies
Cookies. Make-Cookie = create a cookie to send to your browser
Cookies. Name = Name:
Cookies. value = value:
Cookies. Set = You just sent the following cookie to your browser:

Sessions. Title = sessions example
Sessions. ID = session ID:
Sessions. Created = created:
Sessions. lastaccessed = Last accessed:
Sessions. Data = the following data is in your session:
Sessions. adddata = add data to your session
Sessions. dataname = Name of session attribute:
Sessions. datavalue = value of session attribute:

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------------------

Java operations on the properties configuration file

Package com. yorsun;

Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. filenotfoundexception;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. util. properties;

Import javax. servlet. servletcontext;
Import javax. servlet. http. httpservlet;

Public class propertiesunit {
Private string filename;

Private Properties P;

Private fileinputstream in;

Private fileoutputstream out;

Public propertiesunit (string filename ){
This. filename = filename;
File file = new file (filename );
Try {
In = new fileinputstream (File );
P = new properties ();
P. Load (in );
In. Close ();
} Catch (filenotfoundexception e ){
// Todo auto-generated Catch Block
System. Err. println ("the config. properties file cannot be found! ");
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
System. Err. println ("An error occurred while reading the config. properties file! ");
E. printstacktrace ();
}
}

Public static string getconfigfile (httpservlet HS ){
Return getconfigfile (HS, "config. properties ");
}

Private Static string getconfigfile (httpservlet HS, string configfilename ){
String configfile = "";
Servletcontext SC = HS. getservletcontext ();
Configfile = SC. getrealpath ("/" + configfilename );
If (configfile = NULL | configfile. Equals ("")){
Configfile = "/" + configfilename;
}
// Todo auto-generated method stub
Return configfile;
}

Public void list (){
P. List (system. Out );
}

Public String getvalue (string itemname ){
Return P. getproperty (itemname );
}

Public String getvalue (string itemname, string defaultvalue ){
Return P. getproperty (itemname, defaultvalue );
}

Public void setvalue (string itemname, string value ){
P. setproperty (itemname, value );
}

Public void SaveFile (string filename, string description) throws exception {
Try {
File F = new file (filename );
Out = new fileoutputstream (f );
P. Store (Out, description );
Out. Close ();
} Catch (ioexception ex ){
Throw new exception ("the specified configuration file cannot be saved:" + filename );
}
}

Public void SaveFile (string filename) throws exception {
SaveFile (filename ,"");
}

Public void SaveFile () throws exception {
If (filename. Length () = 0)
Throw new exception ("the name of the configuration file to be saved must be specified ");
SaveFile (filename );
}

Public void deletevalue (string value ){
P. Remove (value );
}

Public static void main (string ARGs []) {
String file = "/Eclipse/workspace/newstest/WEB-INF/config. properties ";
// String file = "D: // eclipse // workspace // newstest // WEB-INF // config. properties ";
Propertiesunit Pu = new propertiesunit (File );
Pu. List ();
}

}

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------

Package com. Test. testclass;

Import java. Io. bufferedinputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. filenotfoundexception;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. util. properties;

Public class readpropertiesfile ...{

Public void readpropertiesfile (string filename) throws filenotfoundexception ...{
String STR = "";
Properties prop = new properties ();

Inputstream stream = NULL;

// Read the properties file of this class in the same package
// Stream = getclass (). getclassloader (). getresourceasstream (filename );
System. Out. println ("Path:" + getclass (). getresource (filename ));

// Read the properties file under SRC
String Path = getclass (). getresource ("/"). getpath ();
Stream = new bufferedinputstream (New fileinputstream (new file (path + filename )));

Try ...{
Prop. Load (Stream );
STR = prop. getproperty ("localname ");
System. Out. println ("localname:" + Str );
System. Out. println ("properties:" + Prop );
Stream. Close ();

} Catch (ioexception e )...{
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}

Public static void main (string [] ARGs) throws filenotfoundexception ...{
// Todo auto-generated method stub
New readpropertiesfile (). readpropertiesfile ("config. properties ");

}

}

Certificate --------------------------------------------------------------------------------------------------------------------------------------

// =========================== Sprin configuration file ============================ ====================
<Bean
Id = "userservice"
Class = "com. thtf. ezone. ezesb. JMX. admin. Service. impl. userserviceimpl">
<Property
Name = "filepath"
Value = "config/userinfo. properties"/>
</Bean>

// ========================== Java file ============================== ==================

Package com. thtf. ezone. ezesb. JMX. admin. Service. impl;

Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. util. properties;

Public class userserviceimpl implements userservice {

String filepath = NULL;

Public void setfilepath (string filepath ){
This. filepath = filepath;
}

Public static void main (string dd []) throws exception {

Properties P = new properties ();
Fileinputstream ferr = new fileinputstream (getclass (). getclassloader ()
. Getresource ("") + filepath). tostring (). substring (6); // use substring (6) to remove: file:/try {
P. Load (ferr );
Ferr. Close ();
Set S = P. keyset ();
Iterator it = S. iterator ();
While (it. hasnext ()){
String id = (string) it. Next ();
String value = P. getproperty (ID );
System. Out. println (ID + ": =" + value );
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}

// =================== Databaseconfing. properties file =================================

#----------------------------------
# SQL Server 2000 Data Pipeline Connection Information
#----------------------------------
DP. SD. databasetyp = MSSQL
Databasehost = 127.0.0.1: 1433
Database = formpro
Username = sa
Password = 01
#----------------------------------
# Mysql Data Volume connection information
#----------------------------------
# Databasehost = 127.0.0.1: 3306
# Databasetyp = MySQL
# Database = snow
# Username = root
# Password = 01
// ====================================== Running result ============ ==================

Password: = 01
Databasehost: = 127.0.0.1: 1433
Database: = formpro
DP. SD. databasetyp: = MSSQL
Username: = sa

For your security, please only open the URL with reliable source

Open website {
Share. safelink. Close (); Return false;
} "Href =" http://writeblog.csdn.net/# "> cancel

From: http://hi.baidu.com/hgd0324/blog/item/11f3933f19f4eafd828b1391.html

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.