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();
}
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):
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 theString
class.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.