java配置文件properties

首先大家需要了解在什么情况下需要配置文件:在需要更改代码中的某个变量或者某个值,如果直接在代码中更改则需要更改多处,这个时候如果用配置文件则只需要更改一处即可。

下面来看一下怎样写配置文件:

 首先在你项目的src文件夹下创建file



然后在floder下面创建file文件 ,以properties格式命名




然后创建一个class用来管理properties



具体代码如下:


static Properties props = new Properties();

static{
try {
props.load(PropertiesManger.class.getClassLoader().getResourceAsStream("config/tank.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getProperty(String key){
return props.getProperty(key);
}



在每一处以后可能需要改变的值设立变量:如下

//假如添加10辆坦克
int initTankCount = Integer.parseInt(pm.getProperty("initTankCount"));
for(int i=0; i<initTankCount; i++){
tanks.add(new Tank(50+50*(i+1), 100, false, Direction.D, this));
}



最后在配置文件.properties文件中这样写

initTankCount=10


保存运行,是不是成功了大笑



发布了34 篇原创文章 · 获赞 24 · 访问量 5019

猜你喜欢

转载自blog.csdn.net/wzg199538/article/details/47340547