配置文件读取

前言:项目中某些属性是通过配置文件配置的,然后读取配置文件来获取这些属性,通常都是通过配置.properties文件来设置属性。但事实上,我们可以配置任意格式的文件来配置属性,然后读取,并不局限于.properties文件。只要文件内容的格式符合key-value这样的即可读取,例如:url=csdn.com(url是key,csdn.com是value)。代码如下:

/**
 * 文件名:ReadProperties.java<br/>
 * 创建时间:2015-7-29 下午03:11:14<br/>
 * 创建者:Administrator<br/>
 * 修改者:暂无<br/>
 * 修改简述:暂无<br/>
 * 修改详述:
 * <p>
 * 暂无<br/>
 * </p>
 * 修改时间:暂无<br/>
 */
package hui.sample.properties.test;

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

/**
 * TODO 读取属性配置文件<br/>
 * <p>
 * TODO 读取和操作属性配置文件,不限于.properties文件,只需求文件内容是key-value形式(如url=pdm.8602.com)<br/>
 * </p>
 * Time:2015-7-29 下午03:11:14<br/>
 * @author Administrator
 * @version 1.0.0
 * @since 1.0.0
 */
public class ReadProperties {

	public static Properties getProperties(String filePath) throws FileNotFoundException, IOException{
		Properties properties = null;
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			properties = new Properties();
			properties.load(new FileInputStream(file));					//文件输入流load到properties对象
		}else {
			System.out.println("文件'"+file.getAbsolutePath()+"'不存在");
		}
		return properties;
	}
	
	public static String getValue(String filePath,String key) throws FileNotFoundException, IOException{
		Properties properties = getProperties(filePath);
		String value = properties.getProperty(key);					//通过key获取value值
		<span style="color:#ff0000;">String localEN = System.getProperty("file.encoding");		//获取本地文件编码
		if (value != null && value != "") {
			value = new String(value.getBytes("ISO-8859-1"), localEN);//进行编码转换,防止乱码
		}</span>
		return value;
	}
	
	public static void main(String[] args) {
		String filePath = "D:\\test.txt";								//用txt文件测试
		String key = "test";
		try {
			System.out.println("======"+getValue(filePath, key));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值