1

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?

4
  • Because that application follows the windows norm of using \r\n for EOL? Commented Jul 16, 2013 at 23:08
  • @BrianRoach And most notably only that norm. =) Commented Jul 16, 2013 at 23:09
  • @J.Steen - Yeah, I was editing my comment when you just commented :) It's worth noting that other, non-braindead applications may figure out a file is delimited with \n Commented Jul 16, 2013 at 23:10
  • @BrianRoach Agreed. Such as notepad++, already mentioned in an answer below. ^^ Commented Jul 16, 2013 at 23:12

3 Answers 3

2

\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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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();
        }
    }
}

1 Comment

BufferedWriter has no such method - you need to use newLine()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.