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


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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值