java配置文件操作_Java 配置文件操作方法

使用类库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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值