Java读取properties文件

29 篇文章 0 订阅

Java读取properties文件

properties 基本知识

xxx.properties文件是一个文本文件,用于程序的属性配置。其语法包含注释和属性配置。

注释:在内容前加#
属性配置:采用“key=value”的形式书写。

properties文件的一个属性配置信息值可以换行,但键不可以换行。值换行用“\”表示。 
properties的属性配置键值前后的空格在解析时候会被忽略。 
properties文件可以只有键而没有值。也可以仅有键和等号而没有值,但无论如何一个属性配置不能没有键。

eg:

#WebDriver\u7c7b\u578b\uff0cInternetExplorerDriver\uff0cFirefoxDriver\uff0cChromeDriver
#webdriver.type=FirefoxDriver
#webdriver.type=InternetExplorerDriver
webdriver.type=ChromeDriver

读取properties文件

使用java.util.Properties读取

    String path = "log4j.properties";
    InputStream in = new FileInputStream(path);
    Properties prop = new Properties(); 
    prop.load(in); 
     for (Object key : prop.keySet()) { 
         System.out.println(key + "=" + prop.get(key)); 
     } 
    is.close();

另外,可以使用storeToXMLstore导出到xml文件中。 OutputStream os1 = new FileOutputStream("C:\ttt.xml"); OutputStream os2 = new FileOutputStream("C:\ttt.properties"); prop.storeToXML(os1, "properties导出的xml配置文件"); prop.store(os2, "properties导出的配置文件"); os1.close(); os2.close();

以相对路径的方式进行读取:

 p.load(TestProperties.class.getResourceAsStream("/stu/ttt.properties")); 
 p.load(TestProperties.class.getClassLoader().getResourceAsStream("ttt.properties");

补充: Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法 p.load(context.getResourceAsStream(path));

需要注意编码问题,在load函数中有说明:假定该流使用 ISO 8859-1 字符编码;也就是每个字节是一个 Latin1 字符。对于非 Latin1 的字符和某些特殊字符,可以使用与字符和字符串字面值所用的类似转义序列。

使用spring读取properties

利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件。

构造如下config.properties文件properties代码

#properties
userDao.class=com.spring.dao.UserDao 

//example codes
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("config.properties"));
BeanFactory factory = (BeanFactory)reg;
UserDao userDao = (UserDao)factory.getBean("userDao");   

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值