25

While developing GUI with Java FX, I seem to get different results with System.getProperty("line.separator"); and "\n" during writing to a file or getting data from internet. What basically is the difference?

Gray
  • 112,334
  • 22
  • 281
  • 349
Tilak Maddy
  • 3,505
  • 2
  • 32
  • 49
  • 1
    There are several strongly related questions. I'm not sure whether one perfectly qualifies as a duplicate, but at least, your question is basically answered here: http://stackoverflow.com/a/33505978/3182664 – Marco13 Apr 22 '16 at 14:16

4 Answers4

41

System.getProperty("line.separator") returns the OS dependent line separator.

On Windows it returns "\r\n", on Unix "\n". So if you want to generate a file with line endings for the current operating systems use System.getProperty("line.separator") or write using a PrintWriter.

wero
  • 31,694
  • 3
  • 55
  • 80
  • So, which do you think is better ? Suggest please. – Tilak Maddy Apr 22 '16 at 14:16
  • @TilakMadichetti depends on the use case. If you want line breaks for your current OS use the first form. What do you want to write? – wero Apr 22 '16 at 14:17
  • I want to write huge list of words into a file and one line gap b/w each word. – Tilak Maddy Apr 22 '16 at 14:19
  • @TilakMadichetti if you generate the linebreak with `\n` and open the file on windows in a bad editor (say notepad), the linebreaks will not be displayed. But again good editors will be able to handle unix and windows linebreaks... – wero Apr 22 '16 at 14:24
13

on the Windows platform, System.getProperty("line.separator") is "\r\n", "\n" (Linux and MacOS X), "\r" (MacOS 9 and older)

EL missaoui habib
  • 1,057
  • 1
  • 14
  • 24
7

System.getProperty("line.separator") is platform dependent:

  • "\n" on UNIX style machines
  • "\r\n" on Windows machines

Whereas "\n" is only "\n".

Dan W
  • 5,620
  • 4
  • 32
  • 44
3

«\n» is the line separator for most operating systems such as Linux/Unix. To ensure the compatibility with any operating system, query this value with System.getproperty

Mario
  • 1,425
  • 10
  • 22