package cn.rocker.readProperties;

 import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties; import org.junit.Test;
import org.springframework.core.io.support.PropertiesLoaderUtils; /**
* @ClassName: PropertiesRead
* @Description: Properties读取配置文件
* @author 112
* @date 2018年3月28日 下午12:46:07
*/
public class PropertiesRead {
@Test
/**
* @Description: 第一种方式:根据文件名使用spring中的工具类PropertiesLoaderUtils进行解析
* filePath是相对路径,文件需在classpath目录下
* 此处为:cn/rocker/readProperties/test/properties/cas.properties
* @author czc
* @date 2018年3月28日 下午1:19:57
* @version V1.0
*/
public void PropertiesLoaderUtilsReadProperties(){
Properties prop = null;
String propertiesPath = "cn/rocker/readProperties/test/properties/cas.properties";
try {
prop = PropertiesLoaderUtils.loadAllProperties(propertiesPath);
String url = prop.getProperty("UnifyUserManager_URL");
System.out.println(url);
//输出:http://139.199.20:8080/sso/UnifyUserManager
} catch (IOException e) {
e.printStackTrace();
}
} @Test
/**
* @Description: 这里贴一下getResourceAsStream方法的源码注释
* Before delegation, an absolute resource name is constructed from
* the given resource name using this algorithm:
• If the name begins with a '/' ('\u002f'), then
the absolute name of the resource is the portion of the name following the '/'.
• Otherwise, the absolute name is of the following form: modified_package_name/name
如果getResourceAsStream的参数以"/"开始,则文件的绝对路径就是/后面的部分
如果getResourceAsStream的参数没有以"/"开始,则文件的路径跟操作文件的类在同一包路径下
* @author czc
* @date 2018年3月28日 下午1:36:34
* @version V1.0
*/
public void ResoueceStreamReadProperties(){
Properties prop = new Properties();
String propertiesPath1 = "cas1.properties";
String propertiesPath2 = "/cas2.properties";
String propertiesPaht3 = "/cn/rocker/readProperties/test/properties/cas3.properties";
try {
InputStream inputStream1 = PropertiesRead.class.getResourceAsStream(propertiesPath1);
prop.load(inputStream1);
String url1 = prop.getProperty("UnifyUserManager_URL");
System.out.println("url1:" + url1); InputStream inputStream2 = PropertiesRead.class.getResourceAsStream(propertiesPath2);
prop.load(inputStream2);
String url2 = prop.getProperty("UnifyUserManager_URL");
System.out.println("url2:" + url2); InputStream inputStream3 = PropertiesRead.class.getResourceAsStream(propertiesPaht3);
prop.load(inputStream3);
String url3 = prop.getProperty("UnifyUserManager_URL");
System.out.println("url3:" + url3); //输出:url1:http://139.199.20:8080/sso/UnifyUserManager
// url2:http://139.199.20:8080/sso/UnifyUserManager
// url3:http://139.199.20:8080/sso/UnifyUserManager
} catch (IOException e) {
e.printStackTrace();
}
}
}

Properties读取properties配置文件-LMLPHP

05-11 03:08