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

Java 讀取 Properties 配置檔完整指南:ClassPath、檔案系統與編碼處理

     編輯:Java 相關知識

Properties 基礎用法

java.util.Properties 繼承自 Hashtable<Object, Object>,專門處理鍵值對配置,支援 load()/store() 讀寫字串流,預設編碼 ISO-8859-1(Java 9+ 可指定 UTF-8)。

場景一:ClassPath 內資源(推薦,打包進 JAR)

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ClasspathPropertiesLoader {
    public static Properties load(String resourcePath) throws IOException {
        Properties props = new Properties();
        // 相對於 ClassPath 根目錄,如 "config/app.properties"
        try (InputStream is = ClasspathPropertiesLoader.class
                .getClassLoader()
                .getResourceAsStream(resourcePath)) {
            if (is == null) {
                throw new IOException("資源未找到: " + resourcePath);
            }
            // Java 9+ 可指定編碼
            // props.load(new InputStreamReader(is, StandardCharsets.UTF_8));
            props.load(is); // 預設 ISO-8859-1
        }
        return props;
    }

    public static void main(String[] args) {
        try {
            Properties props = load("config/database.properties");
            String url = props.getProperty("db.url");
            String user = props.getProperty("db.username");
            System.out.println("URL: " + url);
            System.out.println("User: " + user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

場景二:檔案系統絕對/相對路徑(外部化配置)

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Properties;

public class FileSystemPropertiesLoader {
    public static Properties load(String filePath) throws IOException {
        Properties props = new Properties();
        Path path = Paths.get(filePath);
        
        // 方式 1:Files.newBufferedReader (Java 7+,支援 UTF-8)
        try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            props.load(reader);
        }
        
        // 方式 2:FileInputStream + InputStreamReader (舊版相容)
        /*
        try (InputStream is = new FileInputStream(filePath);
             InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(isr)) {
            props.load(br);
        }
        */
        return props;
    }
}

場景三:Spring Boot 環境下的最佳實踐

不建議手寫 Properties 載入代碼。Spring Boot 提供完整配置綁定機制:

# application.yml
app:
  database:
    url: jdbc:mysql://localhost:3306/mydb
    username: admin
    pool-size: 20

# 配置類綁定
@ConfigurationProperties(prefix = "app.database")
@Data
public class DatabaseConfig {
    private String url;
    private String username;
    private int poolSize;
}

// 啟用配置綁定
@EnableConfigurationProperties(DatabaseConfig.class)
@SpringBootApplication
public class Application { ... }

// 直接注入使用
@Service
public class MyService {
    private final DatabaseConfig config;
    public MyService(DatabaseConfig config) { this.config = config; }
    // 使用 config.getUrl() 等類型安全存取
}

編碼問題完整解決方案

Java 9+ 統一 UTF-8 範本

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Properties;

public class Utf8Properties {
    /** 從 ClassPath 載入 UTF-8 Properties */
    public static Properties loadFromClasspath(String resource) throws IOException {
        Properties props = new Properties();
        try (InputStream is = Utf8Properties.class.getClassLoader().getResourceAsStream(resource)) {
            if (is == null) throw new IOException("Not found: " + resource);
            props.load(new InputStreamReader(is, StandardCharsets.UTF_8));
        }
        return props;
    }

    /** 從檔案系統載入 UTF-8 Properties */
    public static Properties loadFromFile(String path) throws IOException {
        Properties props = new Properties();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8)) {
            props.load(br);
        }
        return props;
    }

    /** 存檔為 UTF-8 Properties */
    public static void storeToFile(Properties props, String path, String comments) throws IOException {
        try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8)) {
            props.store(bw, comments);
        }
    }
}

常見陷阱與避坑指南

  • getProperty 返回 null:鍵名拼寫錯誤、編碼導致鍵名不匹配、資源未打包。排查:props.stringPropertyNames() 列印所有鍵。
  • 預設值處理:props.getProperty("key", "defaultValue") 避免 NPE。
  • 類型轉換:Properties 存字串,需自行轉型。建議:用 Spring @ConfigurationProperties 自動綁定。
  • 多環境配置:application-dev.properties, application-prod.properties 配合 spring.profiles.active。

總結

Java 9+ 原生支援 UTF-8 Properties 讀寫,徹底解決中文亂碼歷史遺留問題。現代 Spring Boot 專案應優先使用 @ConfigurationProperties 類型安全綁定,僅在非 Spring 環境、舊系統維護、獨立工具類中手寫 Properties 載入代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
問題原因解決
中文顯示亂碼Properties 預設 ISO-8859-1,檔案實為 UTF-8Java 9+: props.load(reader) 配合 Files.newBufferedReader(path, UTF_8)
存檔後中文變 Unicode 轉義store() 預設輸出 ISO-8859-1,非 ASCII 轉 \uXXXXJava 9+: props.store(writer, comments) 配合 UTF-8 Writer
舊版 Java (8-) 無原生 UTF-8 支援load/store 不接受 Charset 參數手動用 InputStreamReader/OutputStreamWriter 包裝流