Since the code reading the configuration file in Java is fixed, you can separate the part of the read configuration file as a class that can be reused later. To be able to achieve the purpose of reuse, it is not possible to generate a function for each property in the configuration file to read, we need a common method to read the property, that is, the user gives the property name (as a method parameter) to obtain the value of the corresponding property. Here is the sample code:
1 ImportJava.io.*;2 ImportJava.util.*;3 4 ImportOrg.apache.commons.logging.Log;5 Importorg.apache.commons.logging.LogFactory;6 7 8 Public classConfigure {9 Ten //private static final log log = Logfactory.getlog (Serverconfig.class); One Private StaticProperties config =NULL; A - PublicConfigure () { -Config =NewProperties (); the } - - PublicConfigure (String filePath) { -Config =NewProperties (); + Try { -ClassLoader CL = This. GetClass (). getClassLoader (); + InputStream in; A if(CL! =NULL) { atin =Cl.getresourceasstream (filePath); -}Else { -in =Classloader.getsystemresourceasstream (filePath); - } - config.load (in); - //in.close (); in}Catch(FileNotFoundException e) { - //log.error ("Server configuration file not found"); toSYSTEM.OUT.PRINTLN ("Server configuration file not found"); +}Catch(Exception e) { - //log.error ("Server configuration information read error"); theSYSTEM.OUT.PRINTLN ("Server configuration information read error"); * } $ }Panax Notoginseng - Publicstring GetValue (String key) { the if(Config.containskey (key)) { +String value =Config.getproperty (key); A returnvalue; the}Else { + return""; - } $ } $ - Public intgetvalueint (String key) { -String value =GetValue (key); the intValueint = 0; - Try {WuyiValueint =Integer.parseint (value); the}Catch(NumberFormatException e) { - e.printstacktrace (); Wu returnValueint; - } About returnValueint; $ } -}
Unit tests:
@Test publicvoid configuretest () { new Configure (" Server.properties "); int port = config.getvalueint ("Server.port"); = Config.getvalue ("Server.ip"); = Config.getvalue ("Message.split"); System.out.println ("Port:" + port); SYSTEM.OUT.PRINTLN ("IP:" + IP); System.out.println ("SP:" + sp);
The configuration file is as follows:
Server.port =30000server.ip=127.0.0.1falsemax_error_num=1000 Message.split=\ #message.over =31message.servergetmessage=Yesmessage.wrong= Nomessage.servergetover=Overmessage.serverfindsim=Findmessage.servernotfindsim= Notfind
Common classes for reading. Properties Profiles in Java