Why does \n and (String)System.getProperty(“line.s

2019-01-20 05:07发布

This question already has an answer here:

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

2条回答
别忘想泡老子
2楼-- · 2019-01-20 05:16

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.

查看更多
Luminary・发光体
3楼-- · 2019-01-20 05:16

System.getProperty("line.separator") is different from "\n" in that the former returns the OS line separator (not always \n). \n is just a line feed, and when you open your output file in a program that does not interpret \n as a new line (say, Notepad on Windows) you won't see that new line.

查看更多
登录 后发表回答