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"); //第二个参数是使用一段文字对参数列表进行描述。
}
}
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");
}
}