Search code examples
javatext-filesfilewriterprintwriter

Multiple Lines into One Text File? - Java


How can I save multiple lines into One Text File?

I want to print "New Line" in the same Text File every time the code is executed.

try {
        FileWriter fw = new FileWriter("Test.txt");
        PrintWriter pw = new PrintWriter(fw);

        pw.println("New Line");
        pw.close();
    }
    catch (IOException e)
    {
        System.out.println("Error!");
    }

I'm able to create a new file but can't create a new line every time the code is executed.


Solution

  • Pass true as a second argument to FileWriter to turn on "append" mode.

              FileWriter fw = new FileWriter("filename.txt", true);
    

    That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.