解析Properties文件
简介
Properties文件在Java中主要做为配置文件使用,文件类型为:.properties,格式为文本文件,内容格式为"键=值"。
需要注意的问题: ① 路径问题。② 编码格式问题,在部署或迁移时需要注意该文件的编码格式是否发生变动(一般将该文件编码格式设置为 UTF-8 即可)。
使用注释: # 这里是注释
解析文件
Path:/SpringBoot/src/main/java/config/db.properties
# 这里是注释
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=utf8&useSSL=false
db.username=test
db.password=123456789
方法一:ResourceBundle
import java.util.ResourceBundle;
public class PropertiesUtils {
public static void main(String[] args) {
// path:/SpringBoot/src/main/java/config/db.properties
// baseName:前面不能加/,文件名不能加后缀
ResourceBundle rb = ResourceBundle.getBundle("config/db");
System.out.println(rb.getString("db.username"));
// 非maven项目
// /iProcedure/src/com/config/db-config.properties
// ResourceBundle rb = ResourceBundle.getBundle("com/config/db-config");
}
}
方法二:Properties
常用方法 | 含义 |
---|---|
load(InputStream inStream) | 通过文件流装载指定的文件 |
setProperty(String key, String value) | 设置 键 - 值对 |
getProperty(String key) | 通过参数 key 得到 value |
store(OutputStream out, String comments) | 以适合使用 load 方法加载到 Properties 表中的格式 |
clear() | 清除所有装载的 键 - 值对 |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static void main(String[] args) {
// 路径:位于src下,文件名必须加后缀,前面必须加/
System.out.println(PropertiesUtil.getValueByRelativePath("/config/db.properties", "db.url"));
String absolutePath = "E:/final/SpringBoot/src/main/java/config/db.properties";
System.out.println(PropertiesUtil.getValueByAbsolutePath(absolutePath, "db.username"));
}
/**
* 采用相对路径解析properties文件
*
* @param relativePath
* 相对路径,相对于src
* @param key
* key值
* @return value值
*/
public static String getValueByRelativePath(String relativePath, String key) {
Properties properties = new Properties();
try {
// 利用反射获取对应的字段
// 类名.class
InputStream is = PropertiesUtil.class.getResourceAsStream(relativePath);
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty(key);
}
/**
* 采用绝对路径解析properties文件
*
* @param absolutePath
* 绝对路径
* @param key
* key值
* @return value值
*/
public static String getValueByAbsolutePath(String absolutePath, String key) {
Properties properties = new Properties();
try {
BufferedReader br = new BufferedReader(new FileReader(absolutePath));
properties.load(br);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty(key);
}
}