java.util.Properties 繼承自 Hashtable<Object, Object>,專門處理鍵值對配置,支援 load()/store() 讀寫字串流,預設編碼 ISO-8859-1(Java 9+ 可指定 UTF-8)。
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;
}
}
不建議手寫 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() 等類型安全存取
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文顯示亂碼 | Properties 預設 ISO-8859-1,檔案實為 UTF-8 | Java 9+: props.load(reader) 配合 Files.newBufferedReader(path, UTF_8) |
| 存檔後中文變 Unicode 轉義 | store() 預設輸出 ISO-8859-1,非 ASCII 轉 \uXXXX | Java 9+: props.store(writer, comments) 配合 UTF-8 Writer |
| 舊版 Java (8-) 無原生 UTF-8 支援 | load/store 不接受 Charset 參數 | 手動用 InputStreamReader/OutputStreamWriter 包裝流 |