Create a New Line in Java's Filewriter

Create a new line in Java's FileWriter

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
// ^^^^^^^ will add OS line separator after data

(BTW System.out is also instance of PrintStream).

How do I write to a new line using FileWriter in Java?

You're overwriting the file contents due to the use of new FileWriter(fileName); (read the JavaDoc on that class/constructor). Use new FileWriter(fileName, true); to append to the file instead.

Also note that you'd need to append a newline character ("\n") before the name if the file is not empty otherwise you'll get all the names in one line.

How to make a new line on file writer?

Just add new line symbol:

myWriter.write("\n");

Or system dependent from System.lineSeparator(), but \n will always work.

Newline in FileWriter

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

How to add a new line of text to an existing file in Java?

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

output = new BufferedWriter(new FileWriter(my_file_name, true));

should do the trick

Java FileWriter how to write to next Line

out.write(c.toString());
out.newLine();

here is a simple solution, I hope it works

EDIT:
I was using "\n" which was obviously not recommended approach, modified answer.

FileWriter won't append new lines

When writing the file, you need to include both a newline and a linefeed character.
So, in your toString() method, where you add the "\n" newline, instead add both a linefeed and newline: "\r\n"

Java FileWritter write to new line each time

you can use that

bw.write(input);
bw.newLine();

Try to google first or it is even better read the javadocs http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html



Related Topics



Leave a reply



Submit