在有些時候,在代碼中定義常量,不便於更改。所以這裏寫一點個人竅門。
原本是這樣的:
String nodeUrl ="123"; String pkiId = "456"; String senderId = "789"; String serviceId = "124"; String zdyhGmsfhm = "125"; String zdyhXm = "126"; String zdyhDwbm = "127"; String zdyhDwmc = "128"; String zdyhJh = "129"; String xtmc = "130"; String zdyhIp = "131"; String zdyhMac = "132";
改成
String nodeUrl =PropertyReader.getProperty("nodeUrl");
String pkiId =PropertyReader.getProperty("pkiId");
String senderId = PropertyReader.getProperty("senderId");
String serviceId = PropertyReader.getProperty("serviceId711");
String zdyhGmsfhm = PropertyReader.getProperty("zdyhGmsfhm");
String zdyhXm = PropertyReader.getProperty("zdyhXm");
String zdyhDwbm =PropertyReader.getProperty("zdyhDwbm");
String zdyhDwmc =PropertyReader.getProperty("zdyhDwmc");
String zdyhJh = PropertyReader.getProperty("zdyhJh");
String xtmc = PropertyReader.getProperty("xtmc");
String zdyhIp = PropertyReader.getProperty("zdyhIp");
String zdyhMac = PropertyReader.getProperty("zdyhMac");
propertie文件:
nodeUrl =123
pkiId =456
senderId =789
serviceId707=124
zdyhGmsfhm =125
zdyhXm =126
zdyhDwbm =127
zdyhDwmc =128
zdyhJh =129
xtmc =130
zdyhIp =131
zdyhMac =132
這裏有一點要注意,創建properties文件時不能選錯了文件格式,還有,properties中不需要雙引號把=號後面的括起來。
讀取配置文件的代碼是這樣的:
public static PropertyReader pc = new PropertyReader();
public Properties properties = null;
private PropertyReader() {
this.loadConfig();
}
public static PropertyReader getInstance() {
if (pc == null)
pc = new PropertyReader();
return pc;
}
public static String getProperty(String name) {
return pc.properties.getProperty(name);
}
public void loadConfig() {
try {
properties = new Properties();
//System.out.println(getClass().getResourceAsStream("/src/system.properties"));//這個地方是properties的路勁,相對路徑就好
properties.load(new InputStreamReader(PropertyReader.class.getClassLoader().getResourceAsStream("resources/system.properties"),"GBK"));
} catch (Exception e) {
e.printStackTrace();
}
}
如有錯漏,請大佬評論留言,以便及時更改。