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?
Even though the definition of trim() in oracle website is "Returns a copy of the string, with leading and trailing whitespace omitted."
the documentation omits to say that new line characters (leading and trailing) will also be removed.
In short
String text = readFileAsString("textfile.txt").trim();
will also work for you. (Checked with Java 6)Worked perfectly for me after searching a lot, having failed with every other line.
If you want to remove only line terminators that are valid on the current OS, you could do this:
If you want to make sure you remove any line separators, you can do it like this:
Or, slightly more verbose, but less regexy:
You may want to read your file with a
BufferedReader
. This class can break input into individual lines, which you can assemble at will. The wayBufferedReader
operates recognizes line ending conventions of the Linux, Windows and MacOS worlds automatically, regardless of the current platform.Hence:
Note that
readLine()
does not include the line terminator in the returned string. The code above appends a space to avoid gluing together the last word of a line and the first word of the next line.I find it odd that (Apache) StringUtils wasn't covered here yet.
you can remove all newlines (or any other occurences of a substring for that matter) from a string using the
.replace
methodThis line will replace all newlines with the empty string.
because newline is technically a character you can optionally use the
.replaceChars
method that will replace charactersFYI if you can want to replace simultaneous muti-linebreaks with single line break then you can use
Or replace with a single space