Java学习笔记(十):Properties文件解析及其工具化 - Go语言中文社区

Java学习笔记(十):Properties文件解析及其工具化


一、什么是Properties文件

Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。

二、Properties解析过程及其工具化

首先给出一个student.properties文件
在这里插入图片描述
将properties文件中的键值对保存在HashMap中,并提供根据键取值的方法

package stu.crayue.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* @author Crayue
* @version 2019年11月16日 下午4:07:53
*/
public class PropertiesParser {
	private static final Map<String,String> pool;//properties对象只需要一份即可,设置为静态
	static {
		pool=new HashMap<>();//将所有的键值对放在HashMap里方便查找,加快程序运行速度。
	}
	public PropertiesParser() {
	}
	public static void loadProperties(String filepath) {
		InputStream is = PropertiesParser.class.getResourceAsStream(filepath);
		Properties property = new Properties();
		try {
			property.load(is);//加载文件
			Enumeration<Object> keys = property.keys();//获得文件中的键集合
			while(keys.hasMoreElements()) {//判断集合中是否还有元素
				String key =(String) keys.nextElement();//取得下一个元素,需要强转成String类型
				String value = property.getProperty(key);//根据键取对应的值
				pool.put(key, value);//将键和值放入pool中
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static String value(String key) {
		return pool.get(key);//外部方法根据键取值
	}
	
}

给出一个测试代码

package stu.crayue.about_properties.test;
/**
* @author Crayue
* @version 2019年11月16日 下午4:01:40
*/
import stu.crayue.util.PropertiesParser;

public class Test {
	public static void main(String[] args) {
	PropertiesParser.loadProperties("/student.properties");
	System.out.println(PropertiesParser.value("name"));
	System.out.println(PropertiesParser.value("birthday"));
}

运行结果如下:
在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_42063422/article/details/103100391
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢