1

If I write "println("string")" the code writes "string" and then \n if it's run in Windows, \r\n if it's in Linux.

Is there a way to change the behaviour of the "newline" according to my will? I tried to search some other String method, but couldn't find any that could adapt to this problem.

Obviously the final solution would be "print("String\r\n")" if I want the newline to be Windows-compatible, but it's the last thing I'd want to do.

Thanks for the suggestion

Mewster
  • 1,057
  • 3
  • 11
  • 21
  • Not sure if you change the System property it will be reflect in the "built-in" println() at runtime: http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29 – PeterMmm Jan 17 '14 at 08:00
  • Possible duplicate of http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-character?rq=1 – user Jan 17 '14 at 08:00
  • Not sure.. but you might want to read some about ascii encoding, I guess – Arunkumar Jan 17 '14 at 08:00
  • 1
    Its like you want to override your println function. Create your own PrintStream if you want to have custom function. – Vinayak Pingale Jan 17 '14 at 08:01
  • 1
    how about `print(System.getProperty("line.separator"))`? – Baby Jan 17 '14 at 08:04
  • Bruce14: 5 years old question, already seen but I was searching if there were new methods. Rafa el: exactly what the system already does, and that I'm searching not to do. PeterMmm: will read about this, thanks – Mewster Jan 17 '14 at 08:16
  • try `printf("%n")` then – Baby Jan 17 '14 at 08:38
  • That's something that I don't want to do, as I said. – Mewster Jan 17 '14 at 08:41

1 Answers1

1

A PrintStream uses a BufferedWriter to write, which in turn uses this line separator:

/**
 * Line separator string.  This is the value of the line.separator
 * property at the moment that the stream was created.
 */
private String lineSeparator;

You can thus use System.setProperty("line.separator", "\r\n") to set the default line separator, but it will only affect newly created PrintStreams (e.g. System.out will most likely not be affected).

Njol
  • 3,271
  • 17
  • 32
  • Uhm: I don't understand what you mean with System.out not being affected. You mean it's not retroactive, or that there are cases in which the system won't work? – Mewster Jan 17 '14 at 08:17
  • @user The system property is cached in the stream, thus changing the property will not affect existing streams (i.e. the change is not retroactive). – Njol Jan 17 '14 at 10:08