How to read a configuration file in Java

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/stypace/article/details/38414871

First, the use of org.apache.commons.configuration

You need to use a jar package: Commons-collections-3.2.1.jar, Commons-configuration-1.10.jar, Commons-lang-2.6.jar and Commons-logging-1.2.jar.

Configuration files that can be read: XML and properties

1. Read the XML file

[Java]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;"  > Packagecom.styspace;
  2. Import org.apache.commons.configuration.Configuration;
  3. Import org.apache.commons.configuration.ConfigurationException;
  4. Import org.apache.commons.configuration.XMLConfiguration;
  5. Public class Xmlloadertest {
  6. public static void Main (string[] args) throws configurationexception{
  7. Configuration config = new xmlconfiguration ("Com/styspace/config.xml");
  8. String name = config.getstring ("Account.name");
  9. System.out.println ("Name:" + name);
  10. }
  11. }
  12. </span>

It is important to note that the parameter in config.getstring ("Account.name") is Account.name, which is in XPath format and cannot contain the root element in the XML.

The contents of the. config to use are as follows:

[HTML]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;" ><? XML version= "1.0" encoding="GBK"?>
  2. <Accounts>
  3. <account type="by0003">
  4. <code>100001</code>
  5. <pass>123</pass>
  6. <name> John Doe </name>
  7. <money>1000000.00</money>
  8. </Account>
  9. </Accounts></span>



2. Read the properties file

[Java]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;"  > Packagecom.styspace;
  2. Import org.apache.commons.configuration.Configuration;
  3. Import org.apache.commons.configuration.ConfigurationException;
  4. Import org.apache.commons.configuration.PropertiesConfiguration;
  5. Public class Peropertiesloadertest {
  6. public static void Main (string[] args) throws configurationexception{
  7. Configuration config = new propertiesconfiguration ("com/styspace/config.properties");
  8. String name = config.getstring ("name");
  9. System.out.println ("Name:" + name);
  10. }
  11. }
  12. </span>

The contents of the Config.properties file used are as follows:

[Plain]View PlainCopy
    1. <span style= "Font-family:microsoft yahei;font-size:12px;" >threads.max=50threas.min=2
    2. timout=15.52
    3. Interactive=true
    4. Color=red
    5. Speed=50
    6. Name=default user</span>

Second, using java.util.Properties read

[Java]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;"  > Packagecom.styspace;
  2. Import java.io.IOException;
  3. Import Java.io.InputStream;
  4. Import java.util.Properties;
  5. Public class Propertiestest {
  6. public static void Main (string[] args) {
  7. Propertiestest pt = new Propertiestest ();
  8. try {
  9. Pt.getproperties ();
  10. } catch (IOException e) {
  11. //TODO auto-generated catch block
  12. E.printstacktrace ();
  13. }
  14. }
  15. private void GetProperties () throws IOException {
  16. InputStream InputStream = this.getclass (). getClassLoader (). getResourceAsStream ("com/styspace/  Config.properties ");
  17. SYSTEM.OUT.PRINTLN ("BEGIN!!!");
  18. Properties Properties = new properties ();
  19. try{
  20. Properties.load (InputStream);
  21. }catch (IOException IoE) {
  22. Ioe.printstacktrace ();
  23. }finally{
  24. Inputstream.close ();
  25. }
  26. System.out.println ("Name:" +properties.getproperty ("name"));
  27. }
  28. }
  29. </span>

It is important to note that the Hetclassloader (). getResourceAsStream () parameter is the path under the project root directory, Although Config.properties is the same type of file in the same directory, it cannot be written as getClassLoader (). getResourceAsStream ("Config.properties"), so the program will error, The resulting inputstream is a null value.


ClassLoader () and URLClassLoader () Differences: ClassLoader () can only find files in the SRC directory, while URLClassLoader () can find files in any directory.

Third, the read of the configuration file in spring

1. Classpathxmlapplicationcontext: Loaded from the classpath.

2. Filesystemxmlapplicationcontext: Load from File system.

3, Xmlwebapplicationcontext: Load from the web system.

1. Get Beans using bean factory

[Java]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;" > beanfactory factory = null; //Statement
  2. Classpathresource resource = new Classpathresource ("Spring.xml"); Class path
  3. factory= New Xmlbeanfactory (Resource);
  4. Filesystemresource Filesystemresource = new Filesystemresource ("D:\\ncode\\mcode\\sday02\\src\\spring.xml" ); //file path
  5. factory= New Xmlbeanfactory (Filesystemresource);
  6. //xmlbeanfactory (Parameters can be resource or filesystemresource, etc.
  7. //But cannot be res reason can be viewed: Document part Iii. Core Technologies 6. Resources
  8. //6.2 The Resource interface The description of the IsOpen method);
  9. //inputstreamresource res = new Inputstreamresource (New FileInputStream ("d:\\ncode\\mcode\\sday02\\src\\ Spring.xml "));//system path
  10. HelloService HelloService = Factory.getbean ("Helloserviceimpl", Helloserviceimpl.   Class);
  11. Helloservice.sayhello ();</span>


2. Use context

More advanced Context: Provides text information parsing tools, including support for internationalization, provides a common method for loading file resources, and can send events to beans registered as listeners.

In rare cases, use beanfactory.

[Java]View PlainCopy
  1. <span style="Font-family:microsoft yahei;font-size:12px;" > //From File system
  2. ApplicationContext context = new Filesystemxmlapplicationcontext ("file:d:\\ncode\\mcode\\sday02\\src\\  Spring.xml ");
  3. //From class path
  4. ApplicationContext context = new Classpathxmlapplicationcontext ("Classpath:spring.xml");
  5. HelloService HelloService = Context.getbean ("Helloserviceimpl", Helloserviceimpl.   Class);
  6. Helloservice.sayhello ();</span>


3. Use in Web applications

3.1. Using Xmlwebapplicationcontext

[Java]View PlainCopy
  1. Xmlwebapplicationcontext context = new Xmlwebapplicationcontext ();
  2. The default path/web-inf/applicationcontext.xml
  3. Applicationcontext.xml file name can be any
  4. Re-set the path
  5. Context.setconfiglocations (new string[] {"/web-inf/classes/applicationcontext.xml"});
  6. Set the context for the ServletContext context for the Web application
  7. Context.setservletcontext (Getservletcontext ());
  8. Refresh
  9. Context.refresh ();
  10. Get by ID Name
  11. Hellodao Hellodao = Context.getbean ("Hellodaoimpl", Hellodaoimpl.   Class);
  12. Methods for executing Hellodao objects
  13. Hellodao.sayhello ();

3.2. Using Webapplicationcontextutils Tool class

[Java]View PlainCopy
    1. Get the context object directly using Getwebapplicationcontext (Getservletcontext ())
    2. Webapplicationcontext context=
    3. Webapplicationcontextutils.getwebapplicationcontext (Getservletcontext ());
    4. Context = Webapplicationcontextutils.getrequiredwebapplicationcontext (Getservletcontext ());
    5. SYSTEM.OUT.PRINTLN (context);
    6. Hellodao Hellodao = Context.getbean ("Hellodaoimpl", Hellodaoimpl.   Class);
    7. Hellodao.sayhello ()

The difference between the two is:

1, when using Getwebapplicationcontext (Getservletcontext ()) to obtain the context object, the output of the context object is null, so in use

Context.getbean ("Hellodaoimpl", Hellodaoimpl.class); the exception of a null pointer appears

2, when the use of Getrequiredwebapplicationcontext (Getservletcontext ()); Get the context object when the following bug occurs

Java.lang.IllegalStateException:No Webapplicationcontext found:no Contextloaderlistener registered

How to read a configuration file in Java

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.