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

Java Properties 屬性檔案讀寫通用工具類詳解

     編輯:Java 相關知識

前言

在 Java 開發中,java.util.Properties 是一個核心類別,專門用於讀取與管理配置檔案。不同語言有各自支援的配置格式,如 Python 使用 .ini 搭配 ConfigParser,而 Java 則慣用 .properties 文字檔,採「鍵=值」格式,並以 # 表示註解。這種設計讓使用者無需修改程式碼即可調整參數,極大提升了系統的靈活性。

Properties 核心方法速覽

  • getProperty(String key):依鍵取得對應值
  • load(InputStream inStream):從輸入流載入鍵值對
  • setProperty(String key, String value):設定鍵值對(底層呼叫 Hashtable.put)
  • store(OutputStream out, String comments):將屬性列表寫入輸出流,與 load 互為逆操作
  • clear():清除所有已載入的鍵值對

通用工具類實作

以下提供一套可直接引入專案的 PropertieUtil,涵蓋讀取單一屬性、列印全部內容、寫入屬性三大功能:

package com.javacui.lucene.jdbc;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;

public class PropertieUtil {
    private static Logger logger = Logger.getLogger(PropertieUtil.class);
    private PropertieUtil() { }

    /** 讀取配置檔指定屬性 */
    public static String readValue(String filePath, String key) {
        Properties props = new Properties();
        try {
            if (!filePath.startsWith("/")) filePath = "/" + filePath;
            InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
            props.load(in);
            return props.getProperty(key);
        } catch (Exception e) {
            logger.error(e);
            return null;
        }
    }

    /** 列印配置檔全部內容 */
    public static void readProperties(String filePath) {
        Properties props = new Properties();
        try {
            if (!filePath.startsWith("/")) filePath = "/" + filePath;
            InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
            props.load(in);
            Enumeration<?> en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = props.getProperty(key);
                logger.info(key + ":" + value);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /** 將值寫入配置檔 */
    public static void writeProperties(String fileName, String parameterName, String parameterValue) throws Exception {
        if (fileName.startsWith("/")) fileName = fileName.substring(1);
        String filePath = PropertieUtil.class.getResource("/").getPath() + fileName;
        Properties pps = new Properties();
        try (InputStream in = new BufferedInputStream(new FileInputStream(filePath));
             OutputStream out = new FileOutputStream(filePath)) {
            pps.load(in);
            pps.setProperty(parameterName, parameterValue);
            pps.store(out, "Update " + parameterName + " name");
        }
    }

    public static void main(String[] args) throws Exception {
        readProperties("jdbc.properties");
        // logger.info(readValue("jdbc.properties", "JAVABLOG_WRITE_URL"));
        // writeProperties("test.properties", "test", "test");
    }
}

關鍵注意事項

  • 路徑處理:讀取時路徑需以 / 開頭;寫入時則不能帶 /,且需注意 Maven 專案輸出至 target 目錄,非原始碼目錄。
  • 資源關閉:範例使用 try-with-resources 確保流正確關閉,避免洩漏。
  • 編碼問題:Properties.load/store 預設使用 ISO-8859-1,若含中文建議自行處理編碼轉換。

總結

掌握 Properties 讀寫技巧,配合封裝良好的工具類,能讓配置管理更輕鬆維護。實務上可再擴充支援多環境配置、熱重載等進階功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved