[英]How to remove all the line breaks and paragrah breaks using java for a given text file?
[英]How to remove line breaks from a file in Java?
如何在 Java 中以適用於 Windows 和 Linux 的方式替換字符串中的所有換行符(即沒有回車/換行/換行等操作系統特定問題)?
我試過(注意 readFileAsString 是一個將文本文件讀入字符串的函數):
String text = readFileAsString("textfile.txt");
text.replace("\n", "");
但這似乎不起作用。
如何才能做到這一點?
您需要將text
設置為text.replace()
的結果:
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
這是必要的,因為字符串是不可變的——調用replace
不會更改原始字符串,它返回一個已更改的新字符串。 如果您不將結果分配給text
,則該新 String 將丟失並被垃圾收集。
至於為任何環境獲取換行符字符串——可通過調用System.getProperty("line.separator")
。
正如其他答案中所述,您的代碼不起作用主要是因為String.replace(...)
不會更改目標String
。 (它不能 - Java 字符串是不可變的!) replace
實際上所做的是創建並返回一個新的String
對象,其中的字符根據需要進行了更改。 但是你的代碼然后扔掉了那個String
......
以下是一些可能的解決方案。 哪一個最正確取決於您究竟要做什么。
// #1
text = text.replace("\n", "");
只需刪除所有換行符。 這不適用於 Windows 或 Mac 線路終止。
// #2
text = text.replace(System.getProperty("line.separator"), "");
刪除當前平台的所有行終止符。 這不適用於您嘗試在 Windows 上處理(例如)UNIX 文件的情況,反之亦然。
// #3
text = text.replaceAll("\\r|\\n", "");
刪除所有 Windows、UNIX 或 Mac 行終止符。 但是,如果輸入文件是文本,這將連接單詞; 例如
Goodbye cruel
world.
變成
Goodbye cruelworld.
所以你可能真的想要這樣做:
// #4
text = text.replaceAll("\\r\\n|\\r|\\n", " ");
它用空格1替換每個行終止符。 從 Java 8 開始,您也可以這樣做:
// #5
text = text.replaceAll("\\R", " ");
如果你想用一個空格替換多行終止符:
// #6
text = text.replaceAll("\\R+", " ");
1 - 請注意,#3 和 #4 之間存在細微差別。 序列\\r\\n
表示單個(Windows)行終止符,因此我們需要注意不要將其替換為兩個空格。
此函數將所有空格(包括換行符)規范化為單個空格。 不完全是原始問題所要求的,但可能會在許多情況下完全滿足需要:
import org.apache.commons.lang3.StringUtils;
final String cleansedString = StringUtils.normalizeSpace(rawString);
如果您只想刪除在當前操作系統上有效的行終止符,您可以這樣做:
text = text.replaceAll(System.getProperty("line.separator"), "");
如果要確保刪除任何行分隔符,可以這樣做:
text = text.replaceAll("\\r|\\n", "");
或者,稍微詳細一點,但不那么正則:
text = text.replaceAll("\\r", "").replaceAll("\\n", "");
我猜這會很有效
String s;
s = "try this\n try me.";
s.replaceAll("[\\r\\n]+", "")
str = str.replaceAll("\\r\\n|\\r|\\n", " ");
在搜索了很多之后,對我來說效果很好,其他每一行都失敗了。
windows/linux/mac 下的換行符是不一樣的。 您應該將System.getProperties與屬性 line.separator 一起使用。
String text = readFileAsString("textfile.txt").replaceAll("\n", "");
盡管oracle 網站中trim() 的定義是“返回字符串的副本,省略前導和尾隨空格”。
文檔沒有說新行字符(前導和尾隨)也將被刪除。
簡而言之String text = readFileAsString("textfile.txt").trim();
也會為你工作。 (用 Java 6 檢查)
String text = readFileAsString("textfile.txt").replace("\n","");
.replace 返回一個新字符串,Java 中的字符串是不可變的。
您可能希望使用BufferedReader
讀取您的文件。 這個類可以將輸入分成單獨的行,您可以隨意組合。 無論當前平台如何, BufferedReader
運行方式都會自動識別 Linux、Windows 和 MacOS 世界的行結束約定。
因此:
BufferedReader br = new BufferedReader(
new InputStreamReader("textfile.txt"));
StringBuilder sb = new StringBuilder();
for (;;) {
String line = br.readLine();
if (line == null)
break;
sb.append(line);
sb.append(' '); // SEE BELOW
}
String text = sb.toString();
請注意, readLine()
在返回的字符串中不包含行終止符。 上面的代碼添加了一個空格,以避免將一行的最后一個單詞和下一行的第一個單詞粘在一起。
我覺得奇怪的是(Apache) StringUtils還沒有在這里介紹。
您可以使用.replace
方法從字符串中刪除所有換行符(或任何其他出現的子字符串)
StringUtils.replace(myString, "\n", "");
此行將用空字符串替換所有換行符。
因為換行符在技術上是一個字符,您可以選擇使用.replaceChars
方法來替換字符
StringUtils.replaceChars(myString, '\n', '');
您可以使用 apache commons IOUtils 遍歷該行並將每一行附加到 StringBuilder。 並且不要忘記關閉 InputStream
StringBuilder sb = new StringBuilder();
FileInputStream fin=new FileInputStream("textfile.txt");
LineIterator lt=IOUtils.lineIterator(fin, "utf-8");
while(lt.hasNext())
{
sb.append(lt.nextLine());
}
String text = sb.toString();
IOUtils.closeQuitely(fin);
僅供參考,如果您想用單換行符替換同時的多換行符,那么您可以使用
myString.trim().replaceAll("[\n]{2,}", "\n")
或者用一個空格替換
myString.trim().replaceAll("[\n]{2,}", " ")
您可以使用通用方法將任何字符替換為任何字符。
public static void removeWithAnyChar(String str, char replceChar,
char replaceWith) {
char chrs[] = str.toCharArray();
int i = 0;
while (i < chrs.length) {
if (chrs[i] == replceChar) {
chrs[i] = replaceWith;
}
i++;
}
}
在 Kotlin 和 Java 11 中, String
有lines()
方法,它返回多行字符串中的行列表。 您可以獲取所有行,然后將它們合並為一個字符串。
使用 Kotlin 將變得如此簡單
str.lines().joinToString("")
org.apache.commons.lang.StringUtils#chopNewline
嘗試這樣做:
textValue= textValue.replaceAll("\n", "");
textValue= textValue.replaceAll("\t", "");
textValue= textValue.replaceAll("\\n", "");
textValue= textValue.replaceAll("\\t", "");
textValue= textValue.replaceAll("\r", "");
textValue= textValue.replaceAll("\\r", "");
textValue= textValue.replaceAll("\r\n", "");
textValue= textValue.replaceAll("\\r\\n", "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.