跨平台開發時,硬編碼 \n、\r\n、/、\ 是常見 Bug 來源。Java 提供 System.getProperty() 以鍵值對方式取得當前 JVM 執行平台的標準分隔符,本文整理完整鍵名對照表與可直接使用的工具類。
| 屬性鍵 | 用途 | Windows | Linux/macOS |
|---|---|---|---|
line.separator | 換行符 | \r\n (CRLF) | \n (LF) |
file.separator | 檔案路徑分隔符 | \ | / |
path.separator | CLASSPATH 等路徑列表分隔符 | ; | : |
package com.example.util;
import java.util.Properties;
public final class SeparatorUtils {
private static final Properties PROPS = System.getProperties();
private SeparatorUtils() {} // 防止實例化
/** 取得當前平台行分隔符 */
public static String getLineSeparator() {
return PROPS.getProperty("line.separator");
}
/** 取得當前平台檔案路徑分隔符 */
public static String getFileSeparator() {
return PROPS.getProperty("file.separator");
}
/** 取得當前平台路徑列表分隔符 */
public static String getPathSeparator() {
return PROPS.getProperty("path.separator");
}
/** 示範主程式 */
public static void main(String[] args) {
System.out.println("Line separator: [" + getLineSeparator() + "]");
System.out.println("File separator: [" + getFileSeparator() + "]");
System.out.println("Path separator: [" + getPathSeparator() + "]");
}
}
Windows:
Line separator: [
]
File separator: [\]
Path separator: [;]
Linux:
Line separator: [
]
File separator: [/]
Path separator: [:]
import java.nio.file.FileSystems;
String sep = FileSystems.getDefault().getSeparator(); // 檔案分隔符
Path path = FileSystems.getDefault().getPath("a", "b", "c"); // 自動使用正確分隔符
// 輸出: a\b\c (Windows) 或 a/b/c (Linux)
| Key | Description |
|---|---|
| java.version | JRE 版本 |
| java.vendor | JRE 廠商 |
| java.home | JRE 安裝目錄 |
| java.class.path | 類別路徑 |
| java.library.path | 原生庫搜尋路徑 |
| java.io.tmpdir | 預設暫存目錄 |
| os.name | 作業系統名稱 |
| os.arch | OS 架構 (x86/amd64/aarch64) |
| os.version | OS 版本 |
| user.name | 當前使用者帳號 |
| user.home | 使用者家目錄 |
| user.dir | 當前工作目錄 |
| file.encoding | 預設檔案編碼 (JDK 18+ 預設 UTF-8) |
| sun.jnu.encoding | 檔案系統編碼 |
Path 或 File:Path p = Paths.get("config", "app.properties"); 自動處理分隔符。System.getProperty("path.separator") 而非硬編碼 ; 或 :。writer.write(line + System.lineSeparator()); 或 bw.newLine();。善用 System.getProperty() 與 NIO.2 FileSystems,讓程式碼真正做到 Write Once, Run Anywhere。將上述工具類納入專案通用模組,團隊協作時統一呼叫,徹底杜絕分隔符硬編碼問題。