javaiofilewriter

Create a new line in Java's FileWriter


I have coded the following FileWriter:

try {
    FileWriter writer = new FileWriter(new File("file.txt"), false);

    String sizeX = jTextField1.getText();
    String sizeY = jTextField2.getText();
    writer.write(sizeX);
    writer.write(sizeY);

    writer.flush();
    writer.close();
} catch (IOException ex) {}

Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.

What can be done to solve this?

Thank you.


Solution

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


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