1. 首先在CLASS_PATH目录下创建一个属性文件 取名为 tank.properties( 名字随便起)
在配置文件里填写要使用的常量 格式为: 字符串=数字,等号两侧不允许有空格,例如,initTankCount=15 reProduceTank=5
其中 initTankCount和reProduceTank 表示key ,15 和5表示value
2. 创建一个类 PropertiesMgr.java 用于加载配置文件
package com.wang;
import java.io.IOException;
import java.util.Properties;
public class PropertiesMgr {
static Properties pro=new Properties();
static{
try {
pro.load(PropertiesMgr.class.getClassLoader().getResourceAsStream("tank.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
//防止其他类动态创建对象调用该类的静态方法
PropertiesMgr(){}
public static String getProperty(String key){
return pro.getProperty(key);
}
}
3. 现在就可以在其他类中调用配置文件中的变量
例如 在tankClient.java 中使用initTankCount 变量
int tankCount=Integer.parseInt( PropertiesMgr.getProperty("initTankCount"));