在工作过程中发现开发组的读取配置文件的工具类流程太繁琐,里面的逻辑竟然看了好多遍都看不太懂,个人觉得逻辑不够清晰,因此想要简化一下读取文件的方法,并且让路径变得可控.
废话不多说,下面上代码:
我事先在util包下和templates包下新建了两个内容为name=jack的配置文件.
在Test类的主方法分别调用绝对路径和相对路径的方法,读取配置文件:
package com.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
/**
* @author lc
*/
@SuppressWarnings("all")
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
String path = "E:\\workspace\\spring-boot-demo\\src\\main\\java\\com\\lc\\util\\config.properties";
String data = getPropertyAbsolutely(path);
System.out.println(data);
String data2 = getPropertyRelative("/config.properties");
System.out.println(data2);
}
/**
* 相对路径获取
* @param name
* @return
* @throws IOException
*/
public static String getPropertyRelative(String name) throws IOException {
String strKey = null;
String strValue = null;
Properties properties = new Properties();
properties.load(Test.class.getResourceAsStream(name));
Enumeration enum1 = properties.propertyNames();
while (enum1.hasMoreElements()) {
strKey = (String) enum1.nextElement();
strValue = properties.getProperty(strKey);
}
return strKey+"="+strValue;
}
/**
* 绝对路径获取
* @param path
* @return
* @throws IOException
*/
public static String getPropertyAbsolutely(String path) throws IOException {
String strKey = null;
String strValue = null;
Properties properties = new Properties();
properties.load(new FileInputStream(path));
Enumeration enum1 = properties.propertyNames();
while (enum1.hasMoreElements()) {
strKey = (String) enum1.nextElement();
strValue = properties.getProperty(strKey);
}
return strKey+"="+strValue;
}
}
注意:getResourceAsStream()入参不对会报空指针
eclipse是默认的getResourceAsStream()方法的路径是从/src下面开始的
而idea需要你新建一个标记为resources的文件夹,并放在该标记文件夹的下面即可