Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline in FileWriter

Tags:

java

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.

like image 921
Karl Jamoralin Avatar asked Aug 29 '10 21:08

Karl Jamoralin


4 Answers

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));
like image 192
Tim Stone Avatar answered Oct 30 '22 07:10

Tim Stone


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 :

  • JavaDoc - PrintWriter
  • JavaDoc - Properties available on System.getProperty
like image 39
Colin Hebert Avatar answered Oct 30 '22 08:10

Colin Hebert


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

like image 38
Martin Avatar answered Oct 30 '22 09:10

Martin


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

like image 44
MAK Avatar answered Oct 30 '22 09:10

MAK