1 package cn.rocker.readProperties; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.net.URL; 6 import java.util.Properties; 7 8 import org.junit.Test; 9 import org.springframework.core.io.support.PropertiesLoaderUtils; 10 11 /** 12 * @ClassName: PropertiesRead 13 * @Description: Properties讀取配置文件 14 * @author 112 15 * @date 2018年3月28日 下午12:46:07 16 */ 17 public class PropertiesRead { 18 @Test 19 /** 20 * @Description: 第一種方式:根據文件名使用spring中的工具類PropertiesLoaderUtils進行解析 21 * filePath是相對路徑,文件需在classpath目錄下 22 * 此處為:cn/rocker/readProperties/test/properties/cas.properties 23 * @author czc 24 * @date 2018年3月28日 下午1:19:57 25 * @version V1.0 26 */ 27 public void PropertiesLoaderUtilsReadProperties(){ 28 Properties prop = null; 29 String propertiesPath = "cn/rocker/readProperties/test/properties/cas.properties"; 30 try { 31 prop = PropertiesLoaderUtils.loadAllProperties(propertiesPath); 32 String url = prop.getProperty("UnifyUserManager_URL"); 33 System.out.println(url); 34 //輸出:http://139.199.20:8080/sso/UnifyUserManager 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } 39 40 @Test 41 /** 42 * @Description: 這里貼一下getResourceAsStream方法的源碼注釋 43 * Before delegation, an absolute resource name is constructed from 44 * the given resource name using this algorithm: 45 • If the name begins with a '/' ('\u002f'), then 46 the absolute name of the resource is the portion of the name following the '/'. 47 • Otherwise, the absolute name is of the following form: modified_package_name/name 48 如果getResourceAsStream的參數以"/"開始,則文件的絕對路徑就是/后面的部分 49 如果getResourceAsStream的參數沒有以"/"開始,則文件的路徑跟操作文件的類在同一包路徑下 50 * @author czc 51 * @date 2018年3月28日 下午1:36:34 52 * @version V1.0 53 */ 54 public void ResoueceStreamReadProperties(){ 55 Properties prop = new Properties(); 56 String propertiesPath1 = "cas1.properties"; 57 String propertiesPath2 = "/cas2.properties"; 58 String propertiesPaht3 = "/cn/rocker/readProperties/test/properties/cas3.properties"; 59 try { 60 InputStream inputStream1 = PropertiesRead.class.getResourceAsStream(propertiesPath1); 61 prop.load(inputStream1); 62 String url1 = prop.getProperty("UnifyUserManager_URL"); 63 System.out.println("url1:" + url1); 64 65 InputStream inputStream2 = PropertiesRead.class.getResourceAsStream(propertiesPath2); 66 prop.load(inputStream2); 67 String url2 = prop.getProperty("UnifyUserManager_URL"); 68 System.out.println("url2:" + url2); 69 70 InputStream inputStream3 = PropertiesRead.class.getResourceAsStream(propertiesPaht3); 71 prop.load(inputStream3); 72 String url3 = prop.getProperty("UnifyUserManager_URL"); 73 System.out.println("url3:" + url3); 74 75 //輸出:url1:http://139.199.20:8080/sso/UnifyUserManager 76 // url2:http://139.199.20:8080/sso/UnifyUserManager 77 // url3:http://139.199.20:8080/sso/UnifyUserManager 78 } catch (IOException e) { 79 e.printStackTrace(); 80 } 81 } 82 }