传智播客学习之读取配置文件

这篇博客总结了在JavaWeb开发中读取配置文件的多种方法,包括使用File、Apache Commons Configuration、java.util.Properties、java.util.ResourceBundle、PropertyResourceBundle、class.getResourceAsStream()、class.getClassLoader().getResourceAsStream()、ClassLoader.getSystemResourceAsStream()以及Servlet的getResourceAsStream()。通过这些方法,开发者可以方便地在不同场景下加载和操作配置文件。
摘要由CSDN通过智能技术生成

 

从学习javaweb以为,我们经常会遇到读取配置文件的情况,可是读取配置文件这个问题一直困扰着我,今天有一点时间,在网上搜索了一些相关的资料,整理了一下有关读取资源文件的方法,和大家共同分享。

 

1.       在不使用jar包时,使用如下方式读取,不失为一种方法:
File f = new File(this.getClass().getResource("/").getPath());
f = new File(f.getPath() +"/conf/config.properties");

 

2.       使用Apache的类库

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

PropertiesConfiguration config = new PropertiesConfiguration("file path");
config.getString("your prop name");
config.setProperty("your prop name","prop value ");
config.save();//
保存.

 

3、使用java.util.Properties类的load()方法

InputStream in = lnew BufferedInputStream(new FileInputStream(name));   

Properties p = new Properties();   

p.load(in); 

 

4、使用java.util.ResourceBundle类的getBundle()方法 

ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());  

ResourceBundle读取.properties文件可避免路径问题.

注意:process为文件名,切记不要加 .properties URL是文件里的键名

ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");  

String s = bundle.getString("URL");  

System.out.println(s);  

pURL = s; 

 

5、使用java.util.PropertyResourceBundle类的构造函数

InputStream in = new BufferedInputStream(new FileInputStream(name));   

ResourceBundle rb = new PropertyResourceBundle(in);  

 

6、使用class变量的getResourceAsStream()方法

InputStream in = 类名.class.getResourceAsStream(name);   

Properties p = new Properties();   

p.load(in);  

注意:此方法只适用于资源文件和java类在同一文件夹下使用。

 

7、使用class.getClassLoader()所得到的java.lang.ClassLoadergetResourceAsStream()方法 

InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);   

Properties p = new Properties();   

p.load(in);  

8、使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法,此方法灵活性很强,资源文件可以在任意路径下

InputStream in = ClassLoader.getSystemResourceAsStream(name);   

Properties p = new Properties();   

p.load(in);  

 

 

9Servlet中可以使用javax.servlet.ServletContextgetResourceAsStream()方法

InputStream in = context.getResourceAsStream(path);   

Properties p = new Properties();   

p.load(in);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值