properties 配置 java_java Properties配置文件

Properties ----》 配置文件类 属于Map集合体系的。

Properties的作用:

生成配置文件。

读取配置。

Properties要注意的事项:

往Properties添加数据的时候,千万不要添加非字符串类型的数据,如果添加了非字符串类型的数据,那么properties的处理方式就是进行强制类型转换,强转报错。

如果properties的数据出现了中文字符,那么使用store方法时,千万不要使用字节流,如果使用了字节流,那么默认使用iso8859-1码表进行保存,如果出了中文数据建议使用字符流。

如果修改了properties里面 的数据,一定要重新生成一个配置文件。

package cn.itcast.other;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Map.Entry;

import java.util.Properties;

import java.util.Set;

public class Demo4 {

public static void main(String[] args) throws IOException {

// createProperties();

readProperties();

}

//读取配置文件 ---- 加载配置文件到Properties是使用load方法。

public static void readProperties() throws IOException{

//创建一个Properties

Properties properties = new Properties();

//建立输入字符流对象

FileReader fileReader = new FileReader("f:\\users.properties");

//加载配置文件的数据到Properties是使用load方法。

properties.load(fileReader);

//遍历元素

Set> set = properties.entrySet();

for(Entry entry: set){

System.out.println("键:"+ entry.getKey()+" 值:"+ entry.getValue());

}

//修改狗娃...

properties.setProperty("狗娃", "110");

//重新生成一个配置文件

properties.store(new FileWriter("f:\\users.properties"), "hehe");

}

//创建一个配置文件

public static void createProperties() throws IOException{

//创建一个Properties对象

Properties properties = new Properties();

properties.setProperty("狗娃", "123");

properties.setProperty("狗剩", "234");

properties.setProperty("铁蛋", "456");

//FileOutputStream fileOutputStream = new FileOutputStream("f:\\users.properties");

FileWriter fileWriter = new FileWriter("f:\\users.properties");

//利用Properties生成一个配置文件。

properties.store(fileWriter, "hehe"); //第二个参数是使用一段文字对参数列表进行描述。

}

}

b9e88193f4df?nomobile=yes

Paste_Image.png

Properties实战

需求:

使用porperites文件实现本软件只能试用三次,三次之后提示用户购买正版,退出jvm。

public class Demo5 {

public static void main(String[] args) throws IOException {

//先检查是否存在配置文件

File file = new File("F:\\runtime.properties");

if(!file.exists()){//,如果不存在,创建配置文件

file.createNewFile();

}

//创建一个Properties对象

Properties properties = new Properties();

//加载配置文件

properties.load(new FileReader(file));

//定义一个变量记录运行的次数

int count = 0;

//如果配置文件记录了运行次数,则应该使用配置文件的运行次数

String num = properties.getProperty("num");

if(num!=null){

count = Integer.parseInt(num);

}

//判断是否已经运行了三次

if(count==3){

System.out.println("已经到了使用次数,请购买正版!!88");

System.exit(0);

}

count++;

properties.setProperty("num", count+"");

System.out.println("你已经运行了"+count+"次,还剩余"+(3-count)+"次");

//重新生成配置文件

properties.store(new FileWriter(file), "runtime");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值