Create A New Line In Java's FileWriter


Answer :

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



Try System.getProperty( "line.separator" )



   writer.write(System.getProperty( "line.separator" ));


Try wrapping your FileWriter in a BufferedWriter:



BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();


Javadocs for BufferedWriter here.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable