JAVA讀取屬性文件的幾種方法

1.使用java.util.Properties類的load()方法
示例:Java代碼
InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2.使用java.util.ResourceBundle類的getBundle()方法
示例:Java代碼
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3.使用java.util.PropertyResourceBundle類的構造函數
示例:Java代碼
InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4.使用class變量的getResourceAsStream()方法
示例:ava代碼
InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5.使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例:Java代碼
InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6.使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法
示例:Java代碼
InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

7.使用apache的PropertiesConfiguration類
示例:Java代碼
Configuration config = new PropertiesConfiguration("test.properties");
config.getProperty(key);
補充Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法

示例:Java代碼
InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

    其中name爲properties文件名字.但我在網上發現有人說要寫properties文件的絕對路徑,否則測試   不 能通過.我沒驗證過,有興趣的朋友可以試試.
    
  就我個人而言我是比較偏向用第3方法.我在網上找到一篇介紹的更爲詳細的文章,全文如下:在設計時,我們往往需要訪問一些適合本地修改的配置信息,如果作爲靜態變量,那麼每次修改都需要重新編譯一個class,.config保存此類信息並不適合,這時我們需要ResourceBundle。通過ResourceBundle,我們需要訪問位於/WEB-INF/classes目錄下的一個後綴名爲properties的文本類型文件,從裏面讀取我們需要的值。

Java代碼
Locale locale = Locale.getDefault();

ResourceBundle localResource = ResourceBundle.getBundle("ConnResource", locale);   

String value = localResource.getString("test");   
System.out.println("ResourceBundle: " + value);  
這裏對應了/WEB-INF/class/ConnResource.properties文件內容爲:
test=hello world
打印出來的結果就是hello world  
請注意,這裏我們可以利用Locale和ResourceBundle的這個組合創建國際化的java程序。我們可以把locale實例化爲

Java代碼
new Locale("zh","CN");

通過

Java代碼
ResourceBundle.getBundle("MessagesBundle", locale);

系統將自動尋找MessagesBundle_zh_CN,即定義爲中國大陸地區簡體中文。如果沒有該文件,則會依次尋找MessagesBundle_zh,MessagesBundle,直到找到爲止。

/**

  • 寫入properties信息
  • @param filePath 絕對路徑(包括文件名和後綴名)
  • @param parameterName 名稱
  • @param parameterValue 值
    */

public static void writeProperties(String filePath,String parameterName,String parameterValue) {
Properties props = new Properties();
try {
//如果文件不存在,創建一個新的
File file=new File(filePath);
if(!file.exists()){
ToolKit.writeLog(Setting.class.getName(), "sharedata.properties 文件不存在,創建一個新的!"); file.createNewFile(); }
InputStream fis = new FileInputStream(filePath);
// 從輸入流中讀取屬性列表(鍵和元素對)
props.load(fis);
fis.close();
OutputStream fos = new FileOutputStream(filePath);
props.setProperty(parameterName, parameterValue);
// 以適合使用 load 方法加載到 Properties 表中的格式,
// 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
props.store(fos, parameterName);
fos.close(); // 關閉流 }
catch (IOException e) {
System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
writeLog(This.class.getName(), "Visit "+filePath+" for updating "+parameterName+" value error", e); }
}

[代碼] java讀取屬性(相對路徑)
/* filename: 相對路徑+文件名(不要後綴) */
public synchronized static String getPropertyFromFile(String filename, String key) {
ResourceBundle rb = ResourceBundle.getBundle(filename);
return rb.getString(key).trim(); }

/*

  • @Title: readValue
  • @Description: TODO 通過絕對路徑獲取properties文件屬性, 根據key讀取value
  • @param filePath properties文件絕對路徑(包括文件名和後綴)
  • @param key 屬性key
  • @return String 返回value
    */

public static String readValue(String filePath, String key){
Properties props = new Properties();
InputStream in=null;
try{
in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
String value = props.getProperty(key);
return value; }
catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
in.close();//-----------------------------------important
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**

  • 本類主要是對config。properties的密碼進行修改
  • @param args
    */

public static void main(String[] args) {
// TODO Auto-generated method stub
//寫文件 String passwork = “123”;
//更改src的config包下的config.properties文件中的“userPassword”屬性的值
writeProperties("config/config.properties","userPassword",passwork);
//config.properties一定要寫完整
//從文件中取出userPassword,
String decStr=getPropertyFromFile("config/config", "userPassword");
System.out.println("============"+ decStr); }

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class ParsePropertyFile {

public HashMap<String, String> getProperty(String propertyFile) {
    HashMap<String, String> hm = null;
    try {
        Properties props = new Properties();
        InputStream is = new FileInputStream(
                new File(propertyFile).getAbsolutePath());
        props.load(is);
        Set<Object> keys = props.keySet();
        hm = new HashMap<String, String>();
        for (Iterator<Object> it = keys.iterator(); it.hasNext();) {
            String key = (String) it.next();
            hm.put(key, props.getProperty(key));                            
        }
        is.close();    

    } catch (IOException ie) {

    }
    return hm;
}

}

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