在 Java 中使用系統換行字元

1244774083|%Y-%m-%d|agohover

由於一些歷史因素,在不同的作業系統上,習慣使用不同的字元來表示換行符號

Windows \r\n
Unix-like \n
Mac OS 9 \r

在 C/C++ 中,只要用預設的方式(非 binary)來開檔,標準函式庫會自動幫你把 \n 轉換正確的換行字元:

ofstream asc("ascii.txt");
asc << "hello\nworld\n"; // 在 Windows 上會輸出 "hello\r\nworld\r\n"
ofstream bin("binary.txt", ios::binary); // binary mode 會關閉轉換功能
bin << "hello\nworld\n"; // 不管在任何平台皆輸出 "hello\nworld\n"

不幸的是,Java 沒有這個功能:
PrintStream out("output.txt");
out.print("hello\nworld\n"); // 不管任何平台皆輸出 "hello\nworld\n"

這個問題大概有幾個解法,第一是完全改用 println,因為 println 會自動幫你接上系統使用的換行字元:

PrintStream out("output.txt");
out.println("hello");
out.println("world");

或著是使用 System.getProperty("line.separator") 取得系統換行字元,自己做代換:
String str = "hello\nworld\n";
String newline = System.getProperty("line.separator");
out.print(str.replaceAll("\n", newline));

最後是使用 format string 的功能,%n 可以被轉換為系統換行字元:
out.printf("hello%nworld%n");

雖然很容易解決,但我還是頗納悶為何 Java 不能自動幫我轉換。


Comments

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License