您的位置:首页 > 其它

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

2010-01-10 00:14 387 查看
从学习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.ClassLoader的getResourceAsStream()方法
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);

9、Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐