java中读取配置文件的方法

一、使用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.   
  3. import org.apache.commons.configuration.Configuration;  
  4. import org.apache.commons.configuration.ConfigurationException;  
  5. import org.apache.commons.configuration.XMLConfiguration;  
  6. public class xmlLoaderTest {  
  7.   
  8.     public static void main(String[] args) throws ConfigurationException{  
  9.        Configuration config = new XMLConfiguration("com/styspace/config.xml");  
  10.        String name = config.getString("Account.name");  
  11.        System.out.println("name:" + name);  
  12.     }  
  13. }  
  14. </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.   
  3. import org.apache.commons.configuration.Configuration;  
  4. import org.apache.commons.configuration.ConfigurationException;  
  5. import org.apache.commons.configuration.PropertiesConfiguration;  
  6.   
  7. public class peropertiesLoaderTest {  
  8.   
  9.     public static void main(String[] args) throws ConfigurationException{  
  10.        Configuration config = new PropertiesConfiguration("com/styspace/config.properties");  
  11.        String name = config.getString("name");  
  12.        System.out.println("name:" + name);  
  13.     }  
  14. }  
  15. </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.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6.   
  7. public class PropertiesTest {  
  8.     public static void main(String[] args){  
  9.         PropertiesTest pt = new PropertiesTest();  
  10.         try {  
  11.             pt.getProperties();  
  12.         } catch (IOException e) {  
  13.             // TODO Auto-generated catch block  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17.       
  18.     private void getProperties() throws IOException {  
  19.         InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/styspace/config.properties");  
  20.         System.out.println("begin!!!");  
  21.         Properties properties = new Properties();  
  22.         try{  
  23.             properties.load(inputStream);  
  24.         }catch (IOException ioE){  
  25.             ioE.printStackTrace();  
  26.         }finally{  
  27.             inputStream.close();  
  28.         }  
  29.         System.out.println("name:"+properties.getProperty("name"));  
  30.     }  
  31. }  
  32. </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.       
  3.     ClassPathResource resource = new ClassPathResource("spring.xml");//类路径  
  4.     factory= new XmlBeanFactory(resource);   
  5.       
  6.     FileSystemResource fileSystemResource = new FileSystemResource("D:\\Ncode\\mcode\\sday02\\src\\spring.xml");//文件路径  
  7.     factory= new XmlBeanFactory(fileSystemResource);   
  8.       
  9.     //XmlBeanFactory(参数可以是resource或者fileSystemResource等  
  10.     //但是不能是 res 原因可以查看:文档Part III. Core Technologies 6. Resources  
  11.     //中6.2 The Resource interface 有关isOpen方法的说明);  
  12.     //InputStreamResource res = new InputStreamResource(new FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));//系统路径  
  13.   
  14.     HelloService helloService = factory.getBean("helloServiceImpl", HelloServiceImpl.class);  
  15.     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.       
  6.     HelloService helloService =  context.getBean("helloServiceImpl", HelloServiceImpl.class);  
  7.     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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值