1. 程式人生 > >java中讀取配置文件的方法

java中讀取配置文件的方法

oid board t對象 open set itl 方法 getclass count

轉自:http://blog.csdn.net/stypace/article/details/38414871

一、使用org.apache.commons.configuration

需要使用的是jar包:commons-collections-3.2.1.jar、commons-configuration-1.10.jar、commons-lang-2.6.jar和commons-logging-1.2.jar。

可以讀取的配置文件:xml和properties

1、讀取xml文件

[java] view plain copy
  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.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>

需要註意的是config.getString(“Account.name”)中的參數是Account.name,這個參數是XPath格式的,而且不能包含xml中的根元素。

使用到的config.xml內容如下:

[html] view plain copy
  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>李四</name>
  7. <money>1000000.00</money>
  8. </Account>
  9. </Accounts></span>



2、讀取properties文件

[java] view plain copy
  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.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>

使用到的config.properties文件內容如下:

[plain] view plain copy
  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>

二、使用java.util.Properties讀取

[java] view plain copy
  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.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>

需要註意的是hetClassLoader().getResourceAsStream()的參數是項目根目錄下的路徑,盡管config.properties是該該類文件在相同的目錄下,但是不能寫成getClassLoader().getResourceAsStream("config.properties"),這樣程序會報錯,得到的InputStream是null值。


ClassLoader()和URLClassLoader()區別:ClassLoader()只能查找src目錄下的文件,而URLClassLoader()則能查找任意目錄下的文件。

三、spring中配置文件的讀取

1、ClassPathXmlApplicationContext:從類路徑中加載。

2、FileSystemXmlApplicationContext:從文件系統加載。

3、XmlWebApplicationContext:從web系統中加載。

1、使用bean工廠獲取bean

[java] view plain copy
  1. <span style="font-family:Microsoft YaHei;font-size:12px;"> BeanFactory factory = null; //聲明
  2. ClassPathResource resource = new ClassPathResource("spring.xml");//類路徑
  3. factory= new XmlBeanFactory(resource);
  4. FileSystemResource fileSystemResource = new FileSystemResource("D:\\Ncode\\mcode\\sday02\\src\\spring.xml");//文件路徑
  5. factory= new XmlBeanFactory(fileSystemResource);
  6. //XmlBeanFactory(參數可以是resource或者fileSystemResource等
  7. //但是不能是 res 原因可以查看:文檔Part III. Core Technologies 6. Resources
  8. //中6.2 The Resource interface 有關isOpen方法的說明);
  9. //InputStreamResource res = new InputStreamResource(new FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));//系統路徑
  10. HelloService helloService = factory.getBean("helloServiceImpl", HelloServiceImpl.class);
  11. helloService.sayHello();</span>


2、使用上下文(Context)

上下文更加高級:提供文本信息解析工具,包括對國際化支持;提供載入文件資源的通用方法,如圖片;可以向註冊為監聽器的bean發送事件。

在很少的情況下,使用BeanFactory。

[java] view plain copy
  1. <span style="font-family:Microsoft YaHei;font-size:12px;"> //從文件系統
  2. ApplicationContext context = new FileSystemXmlApplicationContext("file:D:\\Ncode\\mcode\\sday02\\src\\spring.xml");
  3. //從類路徑
  4. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
  5. HelloService helloService = context.getBean("helloServiceImpl", HelloServiceImpl.class);
  6. helloService.sayHello();</span>


3、在web應用中使用

3.1、使用XmlWebApplicationContext

[java] view plain copy
  1. XmlWebApplicationContext context = new XmlWebApplicationContext();
  2. //默認的路徑/WEB-INF/applicationContext.xml
  3. //applicationContext.xml文件名稱 可以任意起
  4. //重新設置路徑
  5. //context.setConfigLocations(new String[] {"/WEB-INF/classes/applicationContext.xml"});
  6. //設置ServletContext上下下文為web應用程序的上下文
  7. context.setServletContext(getServletContext());
  8. //刷新
  9. context.refresh();
  10. //根據id名稱獲取
  11. HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);
  12. //執行helloDao對象的方法
  13. helloDao.sayHello();

3.2、使用WebApplicationContextUtils工具類

[java] view plain copy
  1. //直接采用getWebApplicationContext(getServletContext()) 獲取context對象
  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()

兩者的區別是:

1、當采用getWebApplicationContext(getServletContext())獲取context對象的時候,輸出的context對象為null 所以在使用

context.getBean("helloDaoImpl", HelloDaoImpl.class);會出現空指針的異常

2、當采用getRequiredWebApplicationContext(getServletContext());獲取context對象的時候 會出現如下bug

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered

java中讀取配置文件的方法