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.)?
I've tried (note readFileAsString is a function that reads a text file into a String):
String text = readFileAsString("textfile.txt");
text.replace("\n", "");
but this doesn't seem to work.
How can this be done?
You need to set
text
to the results oftext.replace()
: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 totext
, then that new String is lost and garbage collected.As for getting the newline String for any environment -- that is available by calling
System.getProperty("line.separator")
.You can use apache commons IOUtils to iterate through the line and append each line to StringBuilder. And don't forget to close the InputStream
Try doing this:
You can use generic methods to replace any char with any char.