傳智播客學習之讀取配置文件

 

從學習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);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章