Java操作Properties文件

利用JDK自带的Properties类即可操作属性文件,示例代码如下:

package com.test.properties;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesDemo {
	public String getValue(String fileName, String key) throws IOException {
		Properties prop = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = new BufferedInputStream(new FileInputStream(fileName));
			prop.load(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			inputStream.close();
		}
		String value = prop.getProperty(key);
		return value;
	}

	public void writeProperties(String fileName, String key, String value) throws IOException {
		Properties prop = new Properties();
		OutputStream outputStream = null;
		try {
			// 将下边文件(example.properties)中的内容读出来,加入到fileName指定的文件中去
			prop.load(new BufferedInputStream(new FileInputStream(
					"E:/Workspace/MyEclipse6/examples/bin/cn/com/huixin/properties/example.properties")));
			outputStream = new BufferedOutputStream(new FileOutputStream(fileName));
			prop.put(key, value);
			prop.setProperty("english", "95");
			prop.store(outputStream, "Properties File Writen Test");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				outputStream.flush();
				outputStream.close();
			}
		}
	}

	public static void main(String[] args) {
		PropertiesDemo demo = new PropertiesDemo();
		String fileName1 = PropertiesDemo.class.getResource("example.properties").getPath();
		String stuname;
		try {
			stuname = demo.getValue(fileName1, "stuname");
			System.out.println("stuname=" + stuname);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String fileName2 = PropertiesDemo.class.getResource("").getPath() + "example2.properties";
		try {
			demo.writeProperties(fileName2, "class", "3-5");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

示例中读取的example.properties文件的内容如下:

stuid = 25
stuname = \u767e\u5ea6
birthday = 2001-10-25
score = 89

生成的example2.properties文件的内容如下:

#Properties File Writen Test
#Sat Mar 24 22:32:01 CST 2012
english=95
stuname=\u767E\u5EA6
stuid=25
birthday=2001-10-25
class=3-5
score=89

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值