程序的配置文件

来源:互联网 发布:js中两个数组合并 编辑:程序博客网 时间:2024/04/29 19:52

程序的配置文件:简单的用properties 复杂的用 xml(文本型的数据库),而使用properties主要是五个方法:1、new ;2、set; 3、get; 4、load; 5、store;

开始时将配置文件放在与src文件夹并列的位置,bin下是运行根目录 会被src文件覆盖。

在paoperties中 # 表示注释

comments参数的作用是在配置文件中加一行#...的注释。

properties要用到io读写。所以要用到io流。对于io不熟悉可以看我前面的io流复习笔记。

下面我们通过两个个实例来理解这个知识点:

一、properties函数的演示

package cn.hncu.property;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class PropertiesDemo {//使用Properties的五个函数 //因为load读入和store写出方法需要与外面的文件相关联,所以要用到io流。即io流的读与写。//这里用到的key与value都是string类型的public static void main(String[] args) {Properties proper=new Properties();//1 new方法FileInputStream fin=null;try {fin =new FileInputStream("qwer.txt");proper.load(fin);//2 load方法String str1=proper.getProperty("Sname");//3 get方法System.out.println(str1);} catch (IOException e) {e.printStackTrace();}FileOutputStream fout=null;try {fout=new FileOutputStream("qwer.txt");proper.setProperty("information", "yiyang");//4 set方法proper.store(fout, null);//5 store方法} catch (IOException e) {System.out.println("error");}try {fin.close();fout.close();} catch (IOException e) {throw new  RuntimeException("关流失败");}}}


二、小程序

实现代码如下

package cn.hncu.property;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;import javax.management.RuntimeErrorException;public class TimesTried {public static void main(String[] args) {//进入住函数的卫条件,防护if(countDemo()){System.out.println("欢迎使用***");}else{System.out.println("使用次数已到,无法继续使用");}}private static boolean countDemo() {int count=0;Properties p=new Properties();File f=new File("An.dat");;FileInputStream fin = null;try {fin=new FileInputStream(f);p.load(fin);String value=p.getProperty("count");count=Integer.parseInt(value);if (count>=5) {System.out.println("使用次数已到,请注册");return false;}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}count++;System.out.println("运行次数为:"+count);//写FileOutputStream fout = null;try {p.setProperty("count", ""+count);fout=new FileOutputStream(f);p.store(fout, null);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fin.close();fout.close();} catch (IOException e) {throw new RuntimeException("关流失败");}return true;}}


0 0
原创粉丝点击