Reputation: 656
I'm making a code to replace a newline character from a string. On Windows, when I use
String.replaceAll(System.getProperty("line.separator"), "\\n");
this works fine, but it fails in UNIX.
What should i use in UNIX ?
Upvotes: 2
Views: 2716
Reputation: 301
The text being received probably contained windows line separators, so replacing just the \n
character had no effect.
If you don't know the origin of the text (or the text contains a mixture of line separators), the following approach can help. First convert windows and mac line separators into unix separators, then convert the unix separators to the system separator.
final String DOS = "\r\n", NIX = "\n", MAC = "\r";
String converted = original.replace(DOS, NIX)
.replace(MAC, NIX)
.replace(NIX, System.lineSeparator());
Upvotes: 0
Reputation: 4075
\n
is correct for Unix. Windows uses \r\n
and Mac uses \r
IIRC.
The problem may lie in the fact that Java, being a multiplatform language, automatically replaces \n
with the system's separator. I don't know Java but I assume this is the case.
Edit: If the code you posted is what you're using, I think I see the problem. String
is a class. It is also immutable in Java. It should instead be this:
String myStr = "abc\ndef";
myStr = myStr.replaceAll(/* params */);
Upvotes: 1