Java如何通过.properties文件获取配置信息

1.如建一个application.properties文件,文件内容如下:

TEST1= ABC
TEST2= DEF

2.java代码处理

public class TestProperties{
	public static String getPropertiesByName() {
		String testValue1 = null;
		String testValue2 = null;
		InputStream in = null;
		String path = "/properties/application.properties";  //路径为classpath即项目的根路径下的properties文件夹下
		try {
			in= TestProperties.class.getClassLoader().getResourceAsStream(path);
			Properties properties = new Properties();
			properties.load(in);
			testValue1 = properties.getProperty("TEST1");
			testValue2 = properties.getProperty("TEST2");
			//结果testValue1值为ABC;testValue2的值为DEF;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return propertiesValue;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44919928/article/details/91411268