1. 程式人生 > >Java中如何去讀取resources.properties檔案

Java中如何去讀取resources.properties檔案

今天遷移郵件管理功能的時候,有個圖片上傳功能,有個訪問路徑是在resources.properties配置,這個專案沒有配置就找不到了。

正好發現了這個問題,就把讀取resource配置檔案的方法提供給大家。

package com.bonatone.knowledge.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ResourcesUtil {
	
	public static String getProperties(String name){
		Properties props = getPropertiesInCache();
		String value = props.getProperty(name); 
		return value;
	}
	
    public static Properties getPropertiesInCache() throws SecurityException {
    	Properties pro = null;
    	if(pro == null){
    		pro = getProperties();
    	}
        return pro;
    }
    
    private static Properties getProperties(){
		try { 
			InputStream in = Thread.currentThread().getContextClassLoader().getResource("resources.properties").openStream();
			Properties props = new Properties();
			props.load(in); 
			in.close(); // 別忘了關流 
			return props;
		} catch (FileNotFoundException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
    }
    
    public static void putPropertiesToCache(){
    	Properties pro = getProperties();
    }
}

最常用讀取properties檔案的方法
InputStream in = getClass().getResourceAsStream("資源Name");這種方式要求properties檔案和當前類在同一資料夾下面。如果在不同的包中,必須使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");
Java中獲取路徑方法
獲取路徑的一個簡單實現

反射方式獲取properties檔案的三種方式

1 反射方式獲取properties檔案最常用方法以及思考:
Java讀取properties檔案的方法比較多,網上最多的文章是"Java讀取properties檔案的六種方法",但在Java應用中,最常用還是通過java.lang.Class類的getResourceAsStream(String name) 方法來實現,但我見到眾多讀取properties檔案的程式碼中,都會這麼幹:
 

InputStream in = getClass().getResourceAsStream("資源Name");

2 獲取路徑的方式:

File fileB = new File( this .getClass().getResource( "" ).getPath());

System. out .println( "fileB path: " + fileB);

3 利用反射的方式獲取路徑:

InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "xx/xx/xx/xx.properties" );

InputStream ips2 = Enumeration . class .getResourceAsStream( "xx.properties" );

InputStream ips3 = Enumeration . class .getResourceAsStream( "xx/xx.properties" );