2

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 ?

1
  • @Tichodroma's edits broke the code. Now it says \\n instead of \n. Commented Jul 12, 2012 at 17:27

2 Answers 2

1

\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 */);
Sign up to request clarification or add additional context in comments.

1 Comment

In my case, from somewhere i receive a text which i have to set it in a string. and when there is a ENTER key pressed in string, it comes in 2 lines, so wanted to replace it with \n so that when new string is executed it displays correctly. When i use in windows, the java code does what it should do, but not in unix. so should i use String.replaceAll("\n", "\\n"); ??
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.