使用类库Properties对配置文件进行读写。Properties是集合Map与流结合的一个类库。继承自HashTable,其键值对类型都为String。
配置文件操作方法步骤:
创建配置文件对象:
Properites pro = new Properties();
加载配置文件
FileInputStream in = new FileInputStream("Properties.ini");
pro.load(in);
获取键对应的值
String value = pro.getProperty("Key");
设置(修改)键值
pro.setProperty("Key","Value");
将配置文件写入文件中
FileOutputStream out = new FileOutputStream("Properties.ini");
pro.store(out,"Comment");
关闭流对象
in.close();
out.close();
eg:采用配置文件记录软件使用次数信息,当次数超过3次数,无法再使用该程序。
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws IOException
{
//关联配置文件到File
File file = new File("Properties.ini");
if(!file.exists())
file.createNewFile();
//关联配置文件到流中
FileInputStream in = new FileInputStream(file);
//创建Properties配置对象
Properties pro = new Properties();
//加载配置文件(通过流加载对应的配置文件)
pro.load(in);
//获取键值
int nCount = 0;
String str = pro.getProperty("CountUsage");
if(str != null)
{
nCount = Integer.parseInt(str);
if(nCount >= 3)
{
System.out.println("已达到使用上限次数!!");
return;
}
}
++nCount;
//写入配置信息到文件中
pro.setProperty("CountUsage", nCount+"");
FileOutputStream out = new FileOutputStream(file);
pro.store(out,"Comment:Usage Count");
//关闭流对象
in.close();
out.close();
}
}
转载于:https://blog.51cto.com/whatever957/1684973