Java讀取.properties配置文件

未經允許不得轉載,謝謝!

/*1.根據配置文件是否被更改進行讀取.properties配置文件的工具類,初始情況下一次性讀取存到map集合中,當文件被更改後對更改的文件的MD5值重新判斷,如果不同則重新讀取*/

代碼如下:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

/**

 * 單例模式創建RWProperties,用於讀取Properties配置文件信息

 */

public class RWProperties{

 

//私有並靜態化本類對象

    private static RWProperties rWProperties = null;

    //創建Map對象

    private  static Map<String, Map<String,String>> proMap = new HashMap<String, Map<String,String>>();

    

    //用於存放文件的MD5值

    private  static Map<String, String> fileHashmap = new HashMap<String, String>();

    //該map存儲默認的配置文件

    private  static Map<String, String> defaultproMap = new HashMap<String, String>();

    

    

    private  Properties pro = null;

    private  InputStream is = null;

    //本類構造函數

    private RWProperties(){};

    /**

     * 拿到配置文件所在目錄,遍歷出其中所有的配置文件,存入到一個String[]集合中

     * @return listFilePath

     */

    public static String[] initmethod(String confPath){

     //配置文件所在目錄名

     String taskconfPath = confPath;

     //拿到目錄所在路徑

     String listfilepath = RWProperties.class.getClassLoader().getResource(taskconfPath).getPath();

     System.out.println(listfilepath);

     //遍歷該目錄下所有的配置文件,存入到String[]數組中

     File listfile = new File(listfilepath);

    

     String[] listFilePath = listfile.list();

     //如果listFilePath下邊還有目錄則循環遍歷知道發現.properties配置文件

     for(String l : listFilePath){

     File innerfile = new File(l);

     if(innerfile.isDirectory()){

     initmethod(l);

     }

     }

    

return listFilePath;

    }

    /**|對外提供獲取本類的一個入口

     * @return

     */

    public static RWProperties getInstance() {

     if(rWProperties==null){

         rWProperties = new RWProperties();  

     }

        return rWProperties;  

   }  

    /**獲取已經讀取過配置文件所有屬性的Map對象,當配置文件修改後,在讀取的時候先比較配置文件的MD5值與靜態map對象中已經存在的MD5值是否相等

     * 如果相等,則說明文件沒有被改動過,直接返回map集合對象

     * 如果不相等,則說明文件被改動過,重新讀取配置文件,返回新的map集合對象

     * @return proMap:包含所有配置信息的Map集合,集合中的形式是: Map<String, Map<String,String>>

     */

    public  Map<String, Map<String,String>> getProMap() {  

    

        String[] listFilePath = initmethod("taskconfPath");

        //System.out.println(listFilePath[0]);

        try {  

         for(int i=0;i<listFilePath.length;i++){

         Map<String, String> innerproMap = new HashMap<String, String>();

         //拿到配置文件的路徑

         String filepath = RWProperties.class.getClassLoader().getResource("taskconfPath/"+listFilePath[i]).getPath();

         //System.out.println(filepath);

         //該配置文件的MD5標識

         String sid = Integer.toString(i);

         //得到該文件的MD5值

         String fileMD5 = FileMd5.getFileMD5(filepath);

         System.out.println("第"+i+"個配置文件生成的MD5值:"+fileMD5);

        

         //獲取fileHashmap中的對應文件的MD5值

         String MD5 = fileHashmap.get("fileMD5"+sid);

         System.out.println("先獲取集合中存儲的第"+i+"個配置文件的MD5值:"+MD5);

         if(MD5==null){

         is = new FileInputStream(filepath);

         pro = new Properties();

         pro.load(is);

         //獲得任務ID

         String TASK_ID = pro.getProperty("TASK_ID");

         Enumeration<String> e = (Enumeration<String>) pro.propertyNames();  

         while (e.hasMoreElements()) {  

         String key =  e.nextElement().toString();  

         String value = pro.get(key).toString();

        

         innerproMap.put(key, value);

        

         }

         System.out.println("第"+i+"次讀信息到innerproMap中:"+innerproMap);

         proMap.put(TASK_ID, innerproMap);

        

         is.close();//關閉流

         //把這個配置文件的MD5值寫入map集合中

         fileHashmap.put("fileMD5"+sid, fileMD5);

         System.out.println("fileHashmap中存在的MD5值:"+fileHashmap);

        

         }else {

        

         if(!MD5.equals(fileMD5)){

         System.out.println("第"+i+"個配置文件的MD5值不相等,要重新讀配該置文件");

        

         //把這個配置文件的MD5值寫入map集合中

             fileHashmap.put("fileMD5"+sid, fileMD5);

            

         is = new FileInputStream(filepath);

         pro = new Properties();

         pro.load(is);

        

         Enumeration<?> e = pro.propertyNames();  

         while (e.hasMoreElements()) {  

         String key = (String) e.nextElement();  

         String value = (String) pro.get(key);  

        

         innerproMap.put(key, value);

         }

         System.out.println("修改後第"+i+"次讀信息到innerproMap中:"+innerproMap);

         //獲得任務ID

         String TASK_ID = pro.getProperty("TASK_ID");

         proMap.put(TASK_ID, innerproMap);

         is.close();//關閉流

}

         }

}

        } catch (IOException e) {  

            e.printStackTrace();  

        }

return proMap;

     

    }  

    /**

     * 獲取默認的配置文件中的信息存入到defaultproMap集合中

     * @return defaultproMap:包含所有默認的配置文件信息,格式是:Map<String,String>

     */

    public Map<String,String> getDefaultProMap(){

     try {  

     //拿到默認的配置文件的路徑

         String defaultpath = RWProperties.class.getClassLoader().getResource("default.properties").getPath();

         //讀入流

is = new FileInputStream(defaultpath);

pro.load(is);

//遍歷出所有的配置信息,以鍵值對的形式存入到defaultproMap集合中

Enumeration<?> e = pro.propertyNames();  

while (e.hasMoreElements()) {  

String key = (String) e.nextElement();  

String value = (String) pro.get(key);  

defaultproMap.put(key, value);

}

is.close();

         

    } catch (IOException e) {  

        e.printStackTrace();  

    }

return defaultproMap;

 

    }

 

/**

 * 根據傳入的屬性名稱獲取配置文件中相應的屬性

 * @param name:配置文件中的屬性名

 * @return property:屬性名對應的屬性值

 */

public String getAttr(String name){

pro = new Properties();

String[] listFilePath = initmethod("taskconfPath");

try {

for(int i=0;i<listFilePath.length;i++){

     //拿到配置文件的路徑

     String filepath = RWProperties.class.getClassLoader().getResource("taskconfPath/"+listFilePath[i]).getPath();

     is = new FileInputStream(filepath);

}

pro.load(is);

String property = pro.getProperty(name);

return property;

} catch (Exception e) {

}

return null;

}

/**

 * 根據傳入的屬性名稱設置配置文件中相應的屬性,該方法達不到,在修改後,再次加載getProMap方法重新獲取參數的map集合,不可用

 * @param name

 * @return

 * @throws IOException

 */

public void setAttr(String name,String value) throws IOException{

pro = new Properties();

 ///保存屬性到配置文件

try {

//String path = RWProperties.class.getClassLoader().getResource(fileName).getPath();

String[] listFilePath = initmethod("taskconfPath");

FileOutputStream out = new FileOutputStream("src/"+"taskconfPath/"+listFilePath[0]);

pro.setProperty(name, value);

pro.store(out,null);

out.flush();

out.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

/**

 * 以List的形式向配置文件中寫入,該方法達不到,在修改後,再次加載getProMap方法重新獲取參數的map集合,不可用

 * @param filename

 * @param list

 * @throws IOException

 */

public  void set(List<String[]> list) throws IOException{

//String path = RWProperties.class.getClassLoader().getResource(fileName).getPath();//這種路徑 src下的配置文件不能與classes下的同步,爲什麼?

String[] listFilePath = initmethod("taskconfPath");

FileOutputStream out = new FileOutputStream("src/"+"taskconfPath/"+listFilePath[0],true);

for (int i = 0; i < list.size(); i++) {

//System.out.println(list.get(i)[0] + list.get(i)[1]);

pro.setProperty(list.get(i)[0], list.get(i)[1]);

}

pro.store(out, null);

out.flush();

out.close();

}

public static void main(String[]args) throws IOException{

//測試初始化時,集合中的信息顯示

RWProperties instance1 = RWProperties.getInstance();

Map<String, Map<String, String>> proMap1 = instance1.getProMap();

System.out.println(proMap1);

//測試修改第一個配置文件的結果

try {

Thread.sleep(10*1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

RWProperties instance2 = RWProperties.getInstance();

Map<String, Map<String, String>> proMap2 = instance2.getProMap();

System.out.println(proMap2);

//測試修改第二個配置文件的結果

try {

Thread.sleep(10*1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

RWProperties instance3 = RWProperties.getInstance();

Map<String, Map<String, String>> proMap3 = instance3.getProMap();

System.out.println(proMap3);

}

}


2. 得到文件的MD5值;

 

import java.io.File;

import java.io.FileInputStream;

import java.math.BigInteger;

import java.security.MessageDigest;

 

public class FileMd5 {

 

/**

 * 根據路徑創建文件,得到該文件的MD5

 * @param filepath

 * @return

 */

public static String getFileMD5(String filepath) {

 File file = new File(filepath);

        if (!file.exists() || !file.isFile()) {  

            return null;  

        }  

        MessageDigest digest = null;  

        FileInputStream in = null;  

        byte buffer[] = new byte[1024];  

        int len;  

        try {  

            digest = MessageDigest.getInstance("MD5");  

            in = new FileInputStream(file);  

            while ((len = in.read(buffer, 0, 1024)) != -1) {  

                digest.update(buffer, 0, len);  

            }  

            in.close();  

        } catch (Exception e) {  

            e.printStackTrace();  

            return null;  

        }  

        BigInteger bigInt = new BigInteger(1, digest.digest());  

        return bigInt.toString(32);  

    }  

}

   
   
   

發佈了19 篇原創文章 · 獲贊 19 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章