In the Web development process, some configuration to be saved to the properties file, this chapter will give a tool class for easy to read the properties file.
Case:
1:config.properties file
Name=\u843d\u82b1\u6709\u610fstr=\u6d41\u6c34\u65e0\u60c5
2:propertiesutil class
PackageCom.gcs.util;ImportJava.io.BufferedInputStream;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.util.Properties; Public classPropertiesutil {Private StaticString default_properties = "file name. Properties"; Private StaticProperties prop; Static{prop=NewProperties (); Try{InputStream is=NewBufferedinputstream (NewFileInputStream (GetPath () +default_properties)); Prop.load (IS); } Catch(Exception e) {e.printstacktrace (); } } Public Staticstring GetProperty (String key) {returnProp.getproperty (key); } Public Staticstring GetProperty (String key, String defaultvalue) {String value=Prop.getproperty (key); if(Value = =NULL) returnDefaultValue; returnvalue; } Public Static BooleanGetbooleanproperty (String name,BooleanDefaultValue) {String value=Prop.getproperty (name); if(Value = =NULL)returnDefaultValue; return(NewBoolean (value)). Booleanvalue (); } Public Static intGetintproperty (String name) {returnGetintproperty (name, 0); } Public Static intGetintproperty (String name,intDefaultValue) {String value=Prop.getproperty (name); if(Value = =NULL)returnDefaultValue; return(NewInteger (value)). Intvalue (); } Public StaticString GetPath () {returnThread.CurrentThread (). Getcontextclassloader (). GetResource (""). GetPath (); } /*** Read the values in the specified properties *@paramProperties File name *@paramname the property to read *@return */ Privatestring Readproper (String properties, string name) {InputStream InputStream= This. GetClass (). getClassLoader (). getResourceAsStream (properties); Properties P=NewProperties (); Try{p.load (InputStream); } Catch(IOException E1) {e1.printstacktrace (); } returnP.getproperty (name); } Public Static voidMain (string[] args) {propertiesutil propertiesutil=NewPropertiesutil (); String name= Propertiesutil.getproperty ("name"); String Str= Propertiesutil.readproper ("config.properties", "str"); System.out.println ("name==" +name+ "," + "str==" +str); }}
Java read. properties file