28

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
  • 115,027
  • 24
  • 293
  • 354
Tilak Madichetti
  • 4,110
  • 5
  • 34
  • 52
  • 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

43

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
  • 32,544
  • 3
  • 59
  • 84
  • So, which do you think is better ? Suggest please. – Tilak Madichetti 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 Madichetti 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
14

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,075
  • 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,718
  • 4
  • 33
  • 44
4

«\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,661
  • 13
  • 22