Java I/O Properties的使用 存取配置文件


package com.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertyDemo {
	/**
	 * 通过配置文件记录访问次数,例子:程序的试用次数。
	 */
	public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			//创建Properties对象
			Properties prop = new Properties();
			//将文件封装在File对象中
			File file = new File("D:/conf.ini");
			//判断文件是否存在,如果不存在就创建
			if(!file.exists()){
				file.createNewFile();
			}
			//将文件对象放入流对象中
			fis = new FileInputStream(file);
			//加载流文件
			prop.load(fis);
			//创建计数器
			int count = 0;
			//从配置文件中获取times的值(次数)
			String times = prop.getProperty("times");
			//判断times是否为空,如果有值存入count中
			if(times!=null){
				count = Integer.parseInt(times);
			}
			//每访问一次count变加1
			count ++;
			//将新的count写入prop中
			prop.setProperty("times", count+"");
			//创建输出流
			fos = new FileOutputStream(file);
			//将配置信息重新写入文件中,并加上注释信息comments(也可不写)
			prop.store(fos, "hahha");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis!=null)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

  

优质内容筛选与推荐>>
1、[转]VC小技巧(9)-----消息循环重载
2、TortoiseSVN使用svn+ssh协议连接服务器时重复提示输入密码
3、CrossOver 字体模糊 发虚 解决办法
4、JetBrains优惠码分享
5、sql中的等于和不等于, '=' ,'!=','<>','is null'....


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号