首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀取 Properties 配置文件完整指南

     編輯:Java 相關知識

Properties 文件基礎

java.util.Properties 繼承自 Hashtable<Object, Object>,專門用於鍵值對配置存儲,支持 key=value、key:value、key value 三種格式,默認編碼 ISO-8859-1(需注意中文處理)。

核心 API

方法說明
load(InputStream)從字節流加載(ISO-8859-1 編碼)
load(Reader)從字符流加載(可指定編碼,推薦)
store(OutputStream, comments)寫入字節流
store(Writer, comments)寫入字符流(可指定編碼)
getProperty(key)獲取值,不存在返回 null
getProperty(key, defaultValue)獲取值,不存在返回默認值
setProperty(key, value)設置屬性(自動轉字符串)

標準讀取模式

1. 類路徑加載(最常用)

public Properties loadFromClasspath(String path) {
    Properties props = new Properties();
    try (InputStream is = getClass().getClassLoader().getResourceAsStream(path)) {
        if (is == null) {
            throw new IllegalArgumentException("配置文件不存在: " + path);
        }
        // 方式一:JDK 9+ 直接用 Reader 指定 UTF-8
        try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            props.load(reader);
        }
        // 方式二:舊版本需手動轉碼
        // props.load(new InputStreamReader(is, "UTF-8"));
    } catch (IOException e) {
        throw new RuntimeException("加載配置失敗: " + path, e);
    }
    return props;
}

2. 文件系統絕對路徑加載

public Properties loadFromFile(String filePath) {
    Properties props = new Properties();
    try (Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)) {
        props.load(reader);
    } catch (IOException e) {
        throw new RuntimeException("讀取文件失敗: " + filePath, e);
    }
    return props;
}

3. Spring 環境下注入

@Configuration
@PropertySource(value = "classpath:app.properties", encoding = "UTF-8")
public class AppConfig {
    @Autowired
    private Environment env;

    public String getValue(String key) {
        return env.getProperty(key);
    }
}

中文亂碼終極解決方案

Properties 歷史包袱:load(InputStream) 強制 ISO-8859-1。三種解決路徑:

  1. JDK 9+ 使用 Reader(推薦):props.load(new InputStreamReader(is, StandardCharsets.UTF_8))
  2. 轉碼工具類:讀取後手動 new String(value.getBytes("ISO-8859-1"), "UTF-8")
  3. 改用 YAML/JSON:現代項目建議遷移到 application.yml,原生支持 UTF-8、層級結構、類型安全

寫入/修改配置文件

public void updateProperty(String filePath, String key, String value) {
    Properties props = loadFromFile(filePath);
    props.setProperty(key, value);
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) {
        props.store(writer, "Updated by application at " + LocalDateTime.now());
    } catch (IOException e) {
        throw new RuntimeException("寫入配置失敗", e);
    }
}

最佳實踐總結

  • 統一編碼 UTF-8:文件保存、讀取、寫入全鏈路 UTF-8
  • try-with-resources:確保流關閉
  • 異常轉換:IOException 包裝為運行時異常,上層統一處理
  • 配置熱更新:Spring @RefreshScope、Apollo/Nacos 等配置中心
  • 敏感信息加密:密碼、密鑰勿明文存儲,使用 Jasypt 或配置中心加密功能
  • 避免硬編碼路徑:優先類路徑,次之環境變量/系統屬性指定外部路徑

常見陷阱

現象原因修正
中文讀取亂碼用 load(InputStream) 讀取 UTF-8 文件改用 load(Reader) 指定 UTF-8
寫入後中文變 Unicode 轉義store 默認輸出 ASCII 轉義用 store(Writer, UTF-8) 寫入
修改不生效只修改內存對象,未 store 回文件調用 store 寫入磁盤
多線程並發修改丟失Properties 非線程安全加鎖或用 ConcurrentHashMap 替代
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved