如何从Java中删除文件中的换行符? [英] How to remove line breaks from a file in Java?
问题描述
如何以一种可在Windows和Linux上运行的方式替换Java中字符串的所有换行符(即没有特定于OS的回车/换行/换行等问题)?
How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line feed/new line etc.)?
我试过(注意readFileAsString是一个将文本文件读入字符串的函数):
I've tried (note readFileAsString is a function that reads a text file into a String):
String text = readFileAsString("textfile.txt");
text.replace("\n", "");
但这似乎不起作用。
如何做到这一点?
推荐答案
你需要设置 text
到的结果text.replace()
:
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
这是必要的,因为字符串是不可变的 - 调用替换
不会更改原始字符串,它会返回一个已更改的新字符串。如果您没有将结果分配给 text
,那么新的String将丢失并收集垃圾。
This is necessary because Strings are immutable -- calling replace
doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text
, then that new String is lost and garbage collected.
As获取任何环境的换行符 - 可通过调用 System.getProperty(line.separator)
获得。
As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator")
.
这篇关于如何从Java中删除文件中的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!