java获取properties 配置文件

根据网上的例子总结了一下。

其中cache.properties放到src下,也可以放到WEB-INF下
4.package test.bwl;
5.
6. import java.io.FileNotFoundException;
7. import java.io.IOException;
8. import java.io.InputStream;
9. import java.util.Properties;
10.
11.public class Test {
12. private static Properties properties = new Properties();
13.
14. public static void main(String[] args) {
15. try {
16. InputStream is = Test. class .getClassLoader().getResourceAsStream( "cache.properties" );
17. properties.load(is);
18. String size = properties.getProperty( "cache.size" );
19. writeLog( "配置成功!" + size);
20. } catch (FileNotFoundException e) {
21. writeLog( "配置文件不存在!" + e.getMessage());
22. } catch (IOException e) {
23. writeLog( "读取配置文件IO错误!" + e.getMessage());
24. }
25. }
26.
27. public static void writeLog(String strLog) {
28. System.out.println(strLog);
29. }
30.}


1.使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
return rb.getString("key");

注:该方法可以读jar包里的文件

2.使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
return rb.getString("key");

3.使用java.util.Properties类的load()方法
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
return p.getProperties("key"); or return p.getProperties("key", "defaultValue");

4.使用class变量的getResourceAsStream()方法
示例: InputStream in = ClassName.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
return p.getProperties("key"); or return p.getProperties("key", "defaultValue");

5.使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = ClassName.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
return p.getProperties("key"); or return p.getProperties("key", "defaultValue");

6.使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);
return p.getProperties("key"); or return p.getProperties("key", "defaultValue");

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
return p.getProperties("key"); or return p.getProperties("key", "defaultValue");



7.读jar外面的文件
FileInputStream fis;
Properties p = new Properties();
fis = new FileInputStream(initfileName);
prop.load(fis);

注:jar文件执行时,注意cmd路径必须与jar路径相同
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值