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

Java Properties 配置文件讀取與遍歷操作完整指南

     編輯:Java 程式設計入門

核心 API 用法


public class PropertiesUtil {
    public static Map loadProperties(String fileName) {
        Properties props = new Properties();
        Map result = new HashMap<>();
        
        // 類加載器獲取資源流(支持 classpath 根路徑)
        try (InputStream in = PropertiesUtil.class.getResourceAsStream(fileName)) {
            if (in == null) {
                throw new IllegalArgumentException("配置文件不存在: " + fileName);
            }
            props.load(in);
            
            // 遍歷鍵值對
            for (String key : props.stringPropertyNames()) {
                String value = props.getProperty(key);
                result.put(key, value);
                System.out.println(key + " = " + value);
            }
        } catch (IOException e) {
            throw new UncheckedIOException("讀取配置失敗: " + fileName, e);
        }
        return result;
    }
    
    public static void main(String[] args) {
        loadProperties("/loginurl.properties"); // classpath 根路徑
    }
}

關鍵技術點解析

1. 資源加載方式

  • Class.getResourceAsStream("/path"):絕對路徑(classpath 根)
  • Class.getResourceAsStream("path"):相對路徑(當前類包下)
  • ClassLoader.getResourceAsStream("path"):始終為 classpath 根路徑

2. 遍歷最佳實踐


// 推薦:stringPropertyNames() 返回 Set,泛型安全
for (String key : props.stringPropertyNames()) { ... }

// 不推薦:keySet() 返回 Set,需轉型
for (Object key : props.keySet()) { ... }

// 不推薦:Enumeration keys() 古老 API
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) { ... }


3. 字符編碼處理

  • Properties 預設使用 ISO-8859-1 讀取
  • 中文需轉碼:new String(value.getBytes("ISO-8859-1"), "UTF-8")
  • 或使用 @PropertySource(encoding = "UTF-8")(Spring 環境)
  • Java 9+ 支持 XML 格式 loadFromXML() 原生 UTF-8

4. 寫入與持久化


public static void saveProperties(Map data, String filePath) {
    Properties props = new Properties();
    props.putAll(data);
    try (FileOutputStream out = new FileOutputStream(filePath)) {
        props.store(out, "Updated at " + LocalDateTime.now());
    } catch (IOException e) {
        throw new UncheckedIOException("寫入配置失敗", e);
    }
}

進階用法

類型安全轉換


int port = Integer.parseInt(props.getProperty("server.port", "8080"));
boolean debug = Boolean.parseBoolean(props.getProperty("debug", "false"));
List hosts = Arrays.asList(props.getProperty("hosts", "").split(","));

多環境配置隔離


// application.properties (默認)
// application-dev.properties (開發)
// application-prod.properties (生產)
// Spring Boot 自動按 active profile 加載覆蓋

屬性佔位符解析


// 原生 Properties 不支持 ${var} 遞歸解析
// 需使用 Spring PropertyPlaceholderConfigurer 或 Apache Commons Configuration

常見坑點避雷

問題原因解決
中文亂碼ISO-8859-1 默認編碼轉碼或用 XML 格式
文件不存在路徑錯誤/未打包進 JAR檢查 classpath、資源文件打包配置
修改不生效JAR 內文件不可寫外置配置文件、Spring Cloud Config
線程不安全Properties 繼承 Hashtable,雖同步但復合操作非原子單次構建後不可變使用、或用 ConcurrentHashMap
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved