Reputation: 228
When I open the newly written file in jGRASP, it contains many lines of text. When I open the same text file in notepad, it contains one line of text with the same data. The transFile is just a variable for the name of the text file that I am making.
FileWriter f = new FileWriter(transFile, true);
BufferedWriter out = new BufferedWriter(f);
out.write(someOutput + "\n");
out.close();
f.close();
I have changed the code to the following and it fixed the problem in notepad.
out.write(someOutput + "\r\n");
Why does this happen?
Upvotes: 1
Views: 7119
Reputation: 29689
You could do it this way also:
public void appendLineToFile(String filename, String someOutput) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.append( someOutput );
bufferedWriter.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Upvotes: 1
Reputation: 76918
The default line separator for windows (historically) is \r\n
. The windows "notepad" app only recognizes that separator.
Java actually knows the default line separator for the system it's running on and makes it available via the system property line.separator
. In your code you could do:
...
out.write(someOutput);
out.newLine();
...
the newLine()
method appends the system's line separator as defined in that property.
Upvotes: 1
Reputation: 409
\r\n is the windows carriage return, which is what notepad will recognize. I'd suggest getting Notepad++ as it's just much much better.
Upvotes: 2