说明:upload.properties属性文件在resources下
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
public class Test {
private static Properties pro ;
static{
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("upload.properties");
try {
pro= new Properties();
pro.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Properties getProperties(){
return pro;
}
//第一种方式
@org.junit.Test
public void test(){
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("upload.properties");
Properties pro = new Properties();
try {
pro.load(inputStream);
String p1 = pro.getProperty("REPOSITORY_PATH");
String p2 = pro.getProperty("IMAGE_BASE_URL");
System.out.println(p1);
System.out.println(p2);
} catch (IOException e) {
e.printStackTrace();
}
}
//启动jvm的时候就加载类,然后通过静态方法获取属性文件,这样就可以在一个工程中的任何地方获取属性文件中的配置了
@org.junit.Test
public void test1(){
Properties properties = Test.getProperties();
String p1 = properties.getProperty("REPOSITORY_PATH");
tring p2 = properties.getProperty("IMAGE_BASE_URL");
System.out.println("p1:"+p1);
System.out.println("p2:"+p2);
}
//第二种方式
@org.junit.Test
public void test2(){
InputStream stream = ClassLoader.getSystemResourceAsStream("upload.properties");
Properties pro = new Properties();
try {
pro.load(stream);
String p = pro.getProperty("REPOSITORY_PATH");
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
}
}
//第三种方式
@org.junit.Test
public void test3(){
ResourceBundle bundle = ResourceBundle.getBundle("upload");
tring string = bundle.getString("REPOSITORY_PATH");
System.out.println("string:"+string);
}
}
原文地址:https://www.cnblogs.com/lingtiaoti/p/9393581.html