views:

2723

answers:

7

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

but this doesn't seem to work.

How can this be done?

I want to remove ALL line breaks from the file as the resulting file will then be used by another part of the program.

+8  A: 

You need to set text to the results of text.replace():

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

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 for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").

Kaleb Brasee
+1, correct. As to the reason: String is **immutable**. The `replace()` method **returns** the desired result. Also see the API docs: http://java.sun.com/javase/6/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29 *Edit:* ah you already edited that yourself in afterwards :)
BalusC
Perhaps `text = text.replace("\r\n", " ").replace("\n", " ");` is a better solution: otherwise words will be "glued" to each other (without the single-space replacement).
Bart Kiers
Yeah, that's possible. It all depends on what type of data you're trying to modify. Sometimes (for data such as COBOL copybooks) you don't want there to be any spaces between the lines.
Kaleb Brasee
True, it all depends on what the OP is trying to do.
Bart Kiers
+1  A: 
String text = readFileAsString("textfile.txt").replace("\n","");

.replace returns a new string, strings in Java are Immutable.

Viktor Klang
A: 

Linebreaks are not the same under windows/linux/mac. You should use System.getProperties with the attribute line.separator.

Aif
May I know why I got -2? I just mentionned that line.separator should be used!
Aif
+3  A: 

If you want to remove only line terminators valid on the current OS, you could do this:

text = text.replaceAll(System.getProperty("line.separator", ""));

If you want to make sure you remove any line separators, you can do it like this:

text = text.replaceAll("\\r|\\n", "");

Or, slightly more verbose, but less regexy:

text = text.replaceAll("\\r", "").replaceAll("\\n", "");
Fabian Steeg
Shouldn't `\\r|\\n` be sufficient as pattern, as long as you replace with an empty string?
Jørn Schou-Rode
@Jørn: True, thanks, updated my answer.
Fabian Steeg
To avoid gluing word together (as discussed in comments to Kaleb's answer) the regex approach could be modified to `text.replaceAll("(\\r|\\n)+", " ")` and (assuming greedy is default in Java?) you will have a solution with just *one* space for each sequence of new line chars.
Jørn Schou-Rode
+3  A: 

Here are some possible solutions. Which one is correct depends on what exactly you are trying to do.

text = text.replace("\n", "");

Simply removes all the newline characters. This does not cope with Windows or Mac line terminations.

text = text.replace(System.getProperty("line.separator"), "");

Removes all line terminators for the current platform. This does not cope with the case where you are trying to process (for example) a UNIX file on Windows, or vice versa.

text = text.replaceAll("\\r|\\n", "");

Removes all Windows, UNIX or Mac line terminators. However, if the input file is text, this will concatenate words; e.g.

Goodbye cruel
world.

becomes

Goodbye cruelworld.

So you might actually want to do this:

text = text.replaceAll("\\r\\n|\\r|\\n", " ");

which replaces each line terminator with a space.

Stephen C
A: 

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 way BufferedReader operates recognizes line ending conventions of the Linux, Windows and MacOS worlds automatically, regardless of the current platform.

Hence:

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();

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.

Thomas Pornin