6

How do you produce a new line in FileWriter? It seems that "\n" does not work.

log = new FileWriter("c:\\" + s.getInetAddress().getHostAddress() + ".txt", true);    
log.append("\n" + Long.toString(fileTransferTime));
log.close();

The file output of the code above is just a long string of numbers without the new line.

4
  • Is the \t in the second line a typo or intentional? Because \n should work - AFAIK. Commented Aug 29, 2010 at 21:58
  • 2
    Your code does not include any \n. Commented Aug 29, 2010 at 22:14
  • Sorry, I meant "\n". I changed it to \t because it seems to work. Commented Aug 30, 2010 at 10:17
  • Unfortunately, all the answers now refer to the \t question...
    – skaffman
    Commented Aug 30, 2010 at 10:31

4 Answers 4

12

I'll take a wild guess that you're opening the .txt file in Notepad, which won't show newlines with just \n.

Have you tried using your system-specific newline character combination?

log.append(System.getProperty("line.separator") + Long.toString(fileTransferTime));
1
  • 1
    Thanks for your inputs! Just found out that Notepad does not show "\n" newlines whereas other editors will. The System.getProperty("line.separator") does the job even if opened in Notepad. Commented Aug 30, 2010 at 12:57
4

You should either encapsulate your FileWriter into a PrintWriter if your goal is to have a formated content, println() will help you. Or use the system property line.separator to have a separator adapted to your Operating System.

System.getProperty("line.separator")

Resources :

0
2

I'm using "\r\n" and it works great for me. Even when opening .txt document in notepad;)

1
  • 1
    To be platform independent you should not hardcode this. E.g. Unix systems use \n. And it's a shame that so much people upvoted this as the other answers are way better.
    – nkr
    Commented Nov 18, 2012 at 14:13
1

Try changing \t to \n in the second line.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.