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();
				}
			}
		}
	}
}

  

posted @ 2013-09-08 22:35  微风夜明  阅读(155)  评论(0编辑  收藏  举报