Java读取利用java.util类Properties读取resource下的properties属性文件


说明: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);
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM