Properties(配置文件类)

来源:互联网 发布:linux系统运维简历 编辑:程序博客网 时间:2024/05/24 07:09
 Properties(配置文件类): 主要用于生产配置文件与读取配置文件的信息。 容器类(属于map体系)
使用Properties生产配置文件:
store(OutputStream out,String comments):
第一个参数是一个输出流对象,第二参数是使用一个字符串描述这个配置文件的信息。

Properties要注意的细节:
1. 如果配置文件的信息一旦使用了中文,那么在使用store方法生成配置文件的时候只能使用字符流解决,如果使用字节流生成配置文件的话,
默认使用的是iso8859-1码表进行编码存储,这时候会出现乱码。

2. 如果Properties中的内容发生了变化,一定要重新使用Properties生成配置文件,否则配置文件信息不会发生变化。

public class Demo4 {public static void main(String[] args) throws IOException {creatProperties();//readProperties();}//读取配置文件的信息 public static void readProperties() throws IOException{//创建Properties对象Properties properties = new Properties();//加载配置文件信息到Properties中properties.load(new FileReader("F:\\persons.properties"));//遍历Set<Entry<Object, Object>> entrys = properties.entrySet();for(Entry<Object, Object> entry  :entrys){System.out.println("键:"+ entry.getKey() +" 值:"+ entry.getValue());}//修改狗娃的密码//把修改后的Properties再生成一个配置文件properties.setProperty("狗娃", "007");properties.store(new FileWriter("F:\\persons.properties"), "hehe");//配置文件的后缀名一般也叫properties}//保存配置文件文件的信息。public static void creatProperties() throws IOException{//创建PropertiesProperties properties = new Properties();properties.setProperty("狗娃", "123");properties.setProperty("狗剩","234");properties.setProperty("铁蛋","345");// 遍历Properties/*Set<Entry<Object, Object>> entrys = properties.entrySet();for(Entry<Object, Object> entry  :entrys){System.out.println("键:"+ entry.getKey() +" 值:"+ entry.getValue());}*///使用Properties生产配置文件://properties.store(new FileOutputStream("F:\\persons.properties"), "haha"); //第一个参数是一个输出流对象,第二参数是使用一个字符串描述这个配置文件的信息。properties.store(new FileWriter("F:\\persons.properties"), "hehe");}}

 需求: 使用properties实现本软件只能 运行三次,超过了三次之后就提示购买正版,退jvm.

1.创建该配置文件
2.创建Properties对象。
3.把配置文件的信息加载到properties中
4.读取配置文件的运行次数
5.判断使用的次数是否已经达到了三次
6.设置配置文件的信息
7.生成一个配置文件

package cn.itcast.other;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;/*  需求: 使用properties实现本软件只能 运行三次,超过了三次之后就提示购买正版,退jvm.  */public class Demo5 {public static void main(String[] args) throws IOException {File file = new File("F:\\count.properties");if(!file.exists()){//如果配置文件不存在,则创建该配置文件file.createNewFile();}//创建Properties对象。Properties properties = new Properties();//把配置文件的信息加载到properties中properties.load(new FileInputStream(file));FileOutputStream fileOutputStream = new FileOutputStream(file);int count = 0; //定义该变量是用于保存软件的运行次数的。//读取配置文件的运行次数String value = properties.getProperty("count");if(value!=null){count = Integer.parseInt(value);}//判断使用的次数是否已经达到了三次,if(count==3){System.out.println("你已经超出了试用次数,请购买正版软件!!");System.exit(0);}count++;System.out.println("你已经使用了本软件第"+count+"次");properties.setProperty("count",count+"");//使用Properties生成一个配置文件properties.store(fileOutputStream,"runtime");}}




0 0
原创粉丝点击