規範 Java 中的 EOL 字符
一、簡介
不同的作業系統使用不同的行結束符(EOL),這可能會導致在系統之間傳輸或處理檔案時出現問題。此外,規範化 EOL 字元意味著透過使用單一格式使它們保持一致,以確保跨平台的一致性。
本教學提供了用於標準化 EOL 字元的不同 Java 方法。
2. 了解 EOL 字符
在 Java 中,EOL 字元表示文字檔案中行的結尾。不同的作業系統使用不同的序列來表示 EOL:
- Unix/Linux:
\n
(換行) - Windows:
\r\n
(回車符後面跟著換行符號) - 舊 Mac:
\r
(回車)
3.使用String.replaceAll()
方法
標準化 EOL 字元的直接方法是使用 Java 的 String 類別及其replaceAll()
方法。讓我們來看看如何實作這種方法:
String originalText = "This is a text\rwith different\r\nEOL characters\n";
String expectedText = "This is a text" + System.getProperty("line.separator")
+ "with different" + System.getProperty("line.separator") + "EOL characters" + System.getProperty("line.separator");
@Test
public void givenText_whenUsingStringReplace_thenEOLNormalized() {
String normalizedText = originalText.replaceAll("\\r\\n|\\r|\\n", System.getProperty("line.separator"));
assertEquals(expectedText, normalizedText);
}
在這個測試方法中,我們利用replaceAll()
方法將所有出現的(“ \r\n
”)、(“ \r
”)或(“ \n
”)替換為System.getProperty(“line.separator”)
,確保行尾字元的獨立於平台的規範化。最後,我們使用assertEquals()
方法驗證expectedText
和normalizedText
之間的相等性。
此方法有效地將所有出現的指定目標字串替換為特定於平台的行分隔符號。
4. 使用 Apache Commons Lang
Apache Commons Lang 提供了一組豐富的字串操作實用程式。透過利用StringUtils
類,我們可以有效地規範文字中的 EOL 字元。這是實現:
@Test
public void givenText_whenUsingStringUtils_thenEOLNormalized() {
String normalizedText = StringUtils.replaceEach(
originalText,
new String[]{"\r\n", "\r", "\n"},
new String[]{System.getProperty("line.separator"), System.getProperty("line.separator"), System.getProperty("line.separator")});
assertEquals(expectedText, normalizedText);
}
在這種方法中,我們利用StringUtils.replaceEach()
方法並傳遞originalText
字串以及包含要替換的目標字串的陣列(“ \r\n
”、“ \r
”、“ \n
”)以及相應的替換從System.getProperty(“line.separator”)
取得的字串。
5.使用Java 8 Stream API
Java 8 的 Stream API 提供了一種現代而簡潔的方法來處理集合或陣列。透過利用此 API,我們可以簡化文字中 EOL 字元的規範化:
@Test
public void givenText_whenUsingStreamAPI_thenEOLNormalized() {
String normalizedText = Arrays.stream(originalText.split("\\r\\n|\\r|\\n"))
.collect(Collectors.joining(System.getProperty("line.separator"))).trim();
assertEquals(expectedText.trim(), normalizedText);
}
最初,我們使用split()
方法和正規表示式模式(“ \r\n|\r|\n
”)將originalText
拆分為標記數組。隨後,我們使用Arrays.stream()
將此陣列轉換為流。最後,我們使用Collectors.joining()
方法連接標記,並使用System.getProperty(“line.separator”)
作為分隔符號。
六,結論
總之,無論是選擇String.replaceAll()
的簡單性、Apache Commons Lang 的穩健性,或是 Java 8 Stream API 的簡潔性,目標都是一致的:協調 EOL 字元以增強程式碼的可讀性和相容性。
與往常一樣,隨附的源代碼可以在 GitHub 上找到。