Properties 配置文件类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yun1996/article/details/78953010

介绍

Properties(配置文件类):主要用于生成配置文件与读取配置文件的信息。属于集合体系的类,继承了Hashtable类,实现了Map接口

因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。
类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNames 或 list 方法,则该调用将失败。

Properties要注意的细节:

1.如果配置文件的信息一旦使用了中文,那么在使用store方法生成配置文件时只能使用字符流生成配置文件,如果使用字节流,默认是使用IOS8859-1编码,这是会出现乱码
2.如果properties中的内容发生了变化,一定重新使用properties生成配置文件。否则配置文件信息将不会发生变化

例子

`
import java.io.FileNotFoundException;
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 Propertiesee {

public static void main(String[] args) throws FileNotFoundException, IOException {
    createproperties();
    readProperties();
}
//保存配置文件信息
public static void createproperties() throws FileNotFoundException, IOException {
//创建properties对象
Properties properties=new Properties();
properties.setProperty("guwa", "123");
properties.setProperty("gousheng", "456");
properties.setProperty("孙悟空", "789");
//遍历properties

// Set

需求:使用PRIPERties实现本软件只能运行三次,超过三次提示购买正版,退出jvm

public class TestP {
    public static void main(String[] args) throws IOException {
        //配置文件,记录次数
        File file=new File("E:\\t\\count.properties");
       if(!file.exists()){
         //如果不存在,就创建
           file.createNewFile();
       }
       //创建Properties对象
       Properties properties=new Properties();
       //把配置信息添加到对象中
       properties.load(new FileInputStream(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+"");
       //应该放在哪里FileOutputStreamout=new FileOutputStream(file)?
       //因为在new FileOutputStream()有清空的作用,所以在load方法之后,或者在后面加true,加true的话,信息是多次写入,不会先清空在写入
       //使用properties生成一个配置文件
       properties.store(new FileOutputStream(file), "runtimes");;

        System.out.println("QQ程序");

    }

}

“`

猜你喜欢

转载自blog.csdn.net/yun1996/article/details/78953010