Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: BufferedWriter skipping newline

Tags:

java

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();
            }
        }
    }
like image 874
softwarematter Avatar asked Nov 01 '10 06:11

softwarematter


People also ask

Does BufferedWriter write on a new line?

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.

How to write in new line in file Java?

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.


2 Answers

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.

like image 71
Ani Avatar answered Oct 10 '22 04:10

Ani


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.

like image 41
Brad Mace Avatar answered Oct 10 '22 03:10

Brad Mace