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

Java 讀取 Properties 配置文件完整教程

     編輯:Java 相關知識

Properties 文件格式詳解

Properties 文件採用 key=value 鍵值對格式,支援註釋(# 或 ! 開頭),是 Java 應用最常用的配置文件格式。

# 數據庫配置
db.host=localhost
db.port=3306
db.name=myapp
db.user=root
db.password=secret

# 服務器配置
server.port=8080
server.context-path=/api

核心 API:java.util.Properties

Properties 繼承自 Hashtable,提供以下關鍵方法:

  • load(InputStream) / load(Reader):加載配置
  • getProperty(String key) / getProperty(String key, String defaultValue):讀取值
  • setProperty(String key, String value):設置值
  • store(OutputStream, String comments) / store(Writer, String comments):持久化

三種常見讀取方式

方式一:FileInputStream(最基礎)

public Properties loadFromFile(String filePath) throws IOException {
    Properties props = new Properties();
    try (FileInputStream fis = new FileInputStream(filePath)) {
        props.load(fis);
    }
    return props;
}

方式二:ClassPath 資源加載(推薦用於項目內部配置)

public Properties loadFromClasspath(String resourcePath) throws IOException {
    Properties props = new Properties();
    try (InputStream is = getClass().getClassLoader().getResourceAsStream(resourcePath)) {
        if (is == null) {
            throw new IllegalArgumentException("配置文件不存在: " + resourcePath);
        }
        props.load(is);
    }
    return props;
}

方式三:Spring @PropertySource / @Value(企業級開發標準)

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    
    @Value("${db.host}")
    private String dbHost;
    
    @Value("${db.port:3306}")  // 支持默認值
    private int dbPort;
    
    // 注入整個 Properties 對象
    @Autowired
    private Environment env;
    
    public void printAll() {
        System.out.println("DB Host: " + dbHost);
        System.out.println("DB Port: " + dbPort);
    }
}

進階技巧與避坑指南

1. 中文亂碼處理

Properties 默認使用 ISO-8859-1 編碼讀取。Java 9+ 可直接用 load(Reader) 指定 UTF-8:

try (FileReader reader = new FileReader(filePath, StandardCharsets.UTF_8)) {
    props.load(reader);
}

舊版本需手動轉碼:

String value = new String(props.getProperty("key").getBytes("ISO-8859-1"), "UTF-8");

2. 多環境配置隔離

# application-dev.properties
# application-prod.properties
# application-test.properties

# Spring Boot 啟動時指定:--spring.profiles.active=prod

3. 類型安全綁定(@ConfigurationProperties)

@Data
@ConfigurationProperties(prefix = "db")
@Component
public class DatabaseProperties {
    private String host;
    private int port;
    private String name;
    private String username;
    private String password;
}

最佳實踐總結

  1. 配置文件放在 src/main/resources,使用 ClassPath 加載
  2. 敏感信息(密鑰、密碼)絕不提交到版本庫,使用環境變量或配置中心
  3. 善用 getProperty(key, defaultValue) 提供合理默認值
  4. 項目中統一封裝 ConfigUtil 工具類,集中管理加載邏輯

掌握 Properties 文件的正確讀取姿勢,能讓應用配置更靈活、部署更簡單、維護更輕鬆。

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