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();
}
}
}
The newLine() method of BufferedWriter class in Java is used to separate the next line as a new line. It is used as a write separator in buffered writer stream.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With