一些基本的方法
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.util.Properties; 6 7 8 public class GetConfigration { 9 10 11 private static Properties prop; 12 13 public static void load(String path){ 14 //這里的path是項目文件的絕對路徑 15 //先獲取項目絕對路徑:Thread.currentThread().getContextClassLoader().getResource("").getPath(); 16 prop= new Properties();// 屬性集合對象 17 FileInputStream fis; 18 try { 19 //System.out.println(path); 20 fis = new FileInputStream(path); 21 prop.load(fis); 22 fis.close();// 關閉流 23 } catch (FileNotFoundException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 30 //參數為要修改的文件路徑 以及要修改的屬性名和屬性值 31 public static Boolean updatePro(String path,String key,String value){ 32 if(prop==null){ 33 load(path); 34 System.out.println("修改前重新加載一遍"); 35 } 36 System.out.println("獲取添加或修改前的屬性值:"+key+"=" + prop.getProperty(key)); 37 prop.setProperty(key, value); 38 // 文件輸出流 39 try { 40 FileOutputStream fos = new FileOutputStream(path); 41 // 將Properties集合保存到流中 42 prop.store(fos, "Copyright (c) Boxcode Studio"); 43 fos.close();// 關閉流 44 } catch (FileNotFoundException e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 return false; 48 } catch (IOException e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 return false; 52 } 53 System.out.println("獲取添加或修改后的屬性值:"+key+"=" + prop.getProperty(key)); 54 return true; 55 } 56 57 //參數為要修改的文件路徑 以及要修改的屬性名和屬性值 58 public static String getPro(String path,String key){ 59 String absolutePath=Thread.currentThread().getContextClassLoader().getResource("").getPath(); 60 if(prop==null){ 61 load(absolutePath+path); 62 //System.out.println("重新加載一遍"); 63 } 64 FileInputStream fis; 65 try { 66 fis = new FileInputStream(absolutePath+path); 67 prop.load(fis);// 將屬性文件流裝載到Properties對象中 68 fis.close();// 關閉流 69 } catch (FileNotFoundException e) { 70 e.printStackTrace(); 71 } catch (IOException e) { 72 e.printStackTrace(); 73 } 74 // System.out.println("查詢到的"+key+"的值:"+prop.getProperty(key)); 75 return prop.getProperty(key); 76 } 77 78 79 }
調用
String sPath=GetConfigration.getPro("config/application.properties","cloudPath");
String score=GetConfigration.getPro("config/application.properties","syncScoreApi");
