-3

So as the title says, I have a file writer and I want to reuse the program multiple times and saving the text onto a new line in the same text document.

Code:

        try {
        File password1 = new File("password.txt");
        if (password1.createNewFile()) {
            System.out.println("File created: " + password1.getName());                         //Creates new file and inputs variables
        } else {
            System.out.println("File already exists:");
        }
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

    if (save) {
        try {
            FileWriter myWriter = new FileWriter("password.txt");                       //Saves newly created file as a txt
            myWriter.write(web + ": " + password);
            myWriter.close();
            System.out.println("Successfully wrote to the file");
        } catch (IOException e) {
            System.out.println("An error occurred");
            e.printStackTrace();
        }


    }
Rhys Keown
  • 29
  • 3
  • 5
    Does this answer your question? [Java FileWriter with append mode](https://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode) – maloomeister Oct 22 '20 at 14:19
  • 2
    Maybe read the documentation? [FileWriter](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileWriter.html#%3Cinit%3E(java.lang.String,boolean)) – David Conrad Oct 22 '20 at 14:19
  • I think just checking just before writing that does the file with that name exist and if existing you can use `hasnextLine()` method of `Scanner` class to check is there something already written or not. – Sumit Singh Oct 22 '20 at 14:21

1 Answers1

0

FileWriter(File file, boolean append): Creates a FileWriter object using specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason

you need to add second parameter to your constructor to enable the append mode:

  FileWriter myWriter = new FileWriter("password.txt", true); 
maximus
  • 716
  • 7
  • 18
  • 1
    [Is it my duty to check for duplicate questions before answering?](https://meta.stackoverflow.com/questions/326622/is-it-my-duty-to-check-for-duplicate-questions-before-answering) – Abra Oct 22 '20 at 14:26
  • Thanks this worked, is there any chance you know how to make the text go onto a new line? – Rhys Keown Oct 22 '20 at 14:28
  • @RhysKeown you can use BufferedWriter class for that. BufferedWriter br = new BufferedWriter(myWriter); and then br.newLine(); br.write(text); – maximus Oct 22 '20 at 14:42