Search code examples
javastringiosystemstringbuilder

Why does \n and (String)System.getProperty("line.separator"); act differently?


My program takes a input of a text file that has words each separated by a newline and my program takes it and deals with the data, and then I am required to output to a new file whilst keeping the console output.

Now I am wondering why when I append "\n" to my stringBuilder that it prints it out as it were to have a new line in the console, but in the file output, it doesn't take it as a new line and just puts all the words in one line.

When I use newLine, then only does it give a new line in both my console output and my output file. Why is that? What does (String)System.getProperty("line.separator") do that causes this?

String newLine = (String)System.getProperty("line.separator");

 try{
     BufferedReader fileIn = new BufferedReader(new FileReader(fileName));

     stringBuilder.append(newLine);
     while((s = fileIn.readLine()) != null){
        stringBuilder.append(s);
        stringBuilder.append(newLine);//using newLine, 
     }
        String a = stringBuilder.toString();

     if(s== null){
        fileIn.close();
     }

Solution

  • Because on some systems (Linux/Unix) a new line is defined as \n while on others (Windows) it is \r\n. Depending on the software reading the text, it may chose to adhere to this or be more "forgiving" recognizing either or even \r individually.

    Relevant Wikipedia text (https://en.wikipedia.org/wiki/Newline):

    Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A)

    This is also why you can retrieve the system-defined line separater from the System class as you did, instead of, for example, having it be some constant in the String class.