0

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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Let me know if it helps you !
Worked for me :) .... How can i create a new Text File each time a run code? ... Then look for that specific Text File and write to it?
You can easily make new files each time by using different file names each time the above code executes, which will make different files, you can also pass the name of different files using the string array
@imraanstack1, It's good to hear that it worked for you. Please accept the answer if it works for you.
How would i create files with different names? and how would i search for that file and write another line to it?
|
1

You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.

try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
    PrintWriter pw = new PrintWriter(fw)) {
    pw.println("New Line");
} // try-with-resource closes everything.

Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.

Comments

1

You are doing this:

FileWriter fw = new FileWriter("Test.txt");

which is overwriting the file every time you execute that line...

BUT you need instead to append the data to the file

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

take a look at the constructor in the doc

Comments

1

You need to open the file in append mode. You can do that as follows:

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

Here is the documentation for the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.