我如何替换所有的换行符从一个字符串在Java在这样的方式,将工作在Windows和Linux(即没有具体的操作系统的回车/换行/新行等问题)?

我尝试过(注意readFileAsString是一个将文本文件读入String的函数):

String text = readFileAsString("textfile.txt");
text.replace("\n", "");

但这似乎并不奏效。

如何做到这一点呢?


当前回答

我发现奇怪的是(Apache) StringUtils还没有在这里被覆盖。

您可以使用.replace方法从字符串中删除所有换行符(或任何其他出现的子字符串)

StringUtils.replace(myString, "\n", "");

这一行将用空字符串替换所有换行符。

因为换行符在技术上是一个字符,你可以选择使用. replacecars方法来替换字符

StringUtils.replaceChars(myString, '\n', '');

其他回答

您可能希望使用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()在返回的字符串中不包括行结束符。上面的代码添加了一个空格,以避免将一行的最后一个单词和下一行的第一个单词粘合在一起。

你需要将text设置为text.replace()的结果:

String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

这是必要的,因为字符串是不可变的——调用replace并不会改变原始的字符串,它会返回一个被改变的新字符串。如果不将结果赋值给文本,那么新的String将丢失并被垃圾收集。

至于为任何环境获取换行字符串——可以通过调用System.getProperty("line.separator")来获得。

我想这是很有效的

String s;
s = "try this\n try me.";
s.replaceAll("[\\r\\n]+", "")

试着这样做:

 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", "");
String text = readFileAsString("textfile.txt").replace("\n","");

.replace返回一个新字符串,Java中的字符串是不可变的。