Java: BufferedWriter skipping newline
I am using the following function to write a string to a File. The string is formatted with newline characters.
For example, text = "sometext\nsomemoretext\nlastword";
开发者_运维技巧
I am able to see the newline characters of the output file when I do:
type outputfile.txt
However, when I open the text in notepad I can't see the newlines. Everything shows up in a single line.
Why does this happen. How can I make sure that I write the text properly to be able to see correctly (formatted) in notepad.
private static void FlushText(String text, File file)
{
Writer writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (writer != null)
{
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
On windows, new-lines are represented, by convention, as a carriage-return followed by a line-feed (CR + LF), i.e. \r\n
.
From the Newline wikipedia page:
Text editors are often used for converting a text file between different newline formats; most modern editors can read and write files using at least the different ASCII CR/LF conventions. The standard Windows editor Notepad is not one of them (although Wordpad is).
Notepad should display the output correctly if you change the string to:
text = "sometext\r\nsomemoretext\r\nlastword";
If you want a platform-independent way of representing a new-line, use System.getProperty("line.separator");
For the specific case of a BufferedWriter
, go with what bemace suggests.
This is why you should use BufferedWriter.newLine()
instead of hardcoding your line separators. It will take care of picking the correct version for whatever platform you're currently working on.
精彩评论