参考 : https://www.oschina.net/question/2272552_2269641?sort=time
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.util.Properties;
/**
* @Auther: liyue
* @Date: 2019/4/29 10:25
* @Description: 读取properties工具类
*/
public class PropertiesUtil {
public static Properties getProperties(String path) {
try {
//获取配置文件,转换成流
Properties properties = PropertiesLoaderUtils.loadAllProperties(path);
return properties;
} catch (Exception e) {
return null;
}
}
}
或者
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
/**
* @Auther: liyue
* @Date: 2019/4/29 10:25
* @Description: 读取properties工具类
*/
public class PropertiesUtil {
public static Properties getProperties(String path) {
try {
//获取配置文件,转换成流
String propertiesPath = path;
InputStream in = null;
try {
// 开发环境读取
URL url = PropertiesUtil.class.getClassLoader().getResource(propertiesPath);
File file = new File(url.getFile());
in = new FileInputStream(file);
} catch (Exception e) {
}
if (in == null) {
// 打车jar包部署后读取
ClassPathResource classPathResource = new ClassPathResource(propertiesPath);
in = classPathResource.getInputStream();
}
//创建properties对象
Properties properties = new Properties();
//加载流
properties.load(in);
return properties;
} catch (Exception e) {
return null;
}
}
}
本文介绍了在Spring框架中如何使用两种不同的方法读取properties文件,包括利用PropertiesLoaderUtils和ClassPathResource,提供了详细的代码实现。
5046

被折叠的 条评论
为什么被折叠?



