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