Java讀取Properties工具類
本文使用maven環境搭建,JDK版本建議1.8及以上
配置pom文件
maven默認使用jdk1.5編譯代碼,由於此配置文件使用到了jdk1.7的 try(){}...寫法,所以需要在maven的pom文件中引入如下配置。
<properties>
<!-- maven-compiler-plugin 將會使用指定的 JDK 版本將 java 文件編譯為 class 文件(針對編譯運行環境) -->
<maven.compiler.target>1.8</maven.compiler.target>
<!-- maven-compiler-plugin 將會使用指定的 JDK 版本對源代碼進行編譯(針對編譯運行環境) -->
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
可能會遇到的問題:
- 如果出現了下圖所示錯誤
請檢查idea的配置是否如下圖所示(選擇8-Lamdbas.....)
在Resource文件夾下創建properties文件
下面提供一個properties文件的案例,文件名為aliyunOSS.properties
AccessKey=SSSSSSSSSSSS
AccessKeySecret=XXXXXXXX
Buckets=EEEEEEEEEEEEEEEEEEE
EndPoint=oss-cn-beijing.aliyuncs.com
工具類代碼
package cn.rayfoo.util;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by rayfoo@qq.com Luna on 2020/4/15 18:38
* Description : 讀取配置文件工具類
*/
public class PropertiesReader {
//創建Properties對象
private static Properties property = new Properties();
//在靜態塊中加載資源
static {
//使用try(){}.. 獲取數據源
//注意 * 這是jdk1.7開始支持的特性,如果使用的是低版本 需要提升jdk版本 或者更改寫法
try (
InputStream in = PropertiesReader.class.getResourceAsStream("/aliyunOSS.properties");
) {
property.load(in);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取字符串類型的值
* @param key
* @return
*/
public static String get(String key) {
return property.getProperty(key);
}
/**
* 獲取Integer類型的值
* @param key
* @return
*/
public static Integer getInteger(String key) {
String value = get(key);
return null == value ? null : Integer.valueOf(value);
}
/**
* 獲取Boolean類型的值
* @param key
* @return
*/
public static Boolean getBoolean(String key) {
String value = get(key);
return null == value ? null : Boolean.valueOf(value);
}
/**
* 設置一個鍵值對
* @param key
* @param value
*/
public static void set(String key,String value){
property.setProperty(key,value);
}
/**
* 添加一個鍵值對
* @param key
* @param value
*/
public static void add(String key,Object value){
property.put(key,value);
}
}
測試
package cn.rayfoo;
/**
* Created by rayfoo@qq.com Luna on 2020/4/15 19:00
*/
public class TestApp {
public static void main(String[] args) {
System.out.println(PropertiesReader.get("AccessKey"));
System.out.println(PropertiesReader.get("AccessKeySecret"));
System.out.println(PropertiesReader.get("Buckets"));
System.out.println(PropertiesReader.get("EndPoint"));
}
}