0

What I currently have is this

import java.io.*;
import java.security.acl.NotOwnerException;
import java.util.Scanner;

class Main {

  public static void main(String args[])
  {
      try{
    System.out.print("Enter username: ");
    Scanner scanner = new Scanner(System.in);
    String username = scanner.nextLine();
    System.out.print("Enter email: ");
    Scanner scanner2 = new Scanner(System.in);
    String email = scanner.nextLine();
    System.out.print("Enter password: ");
    Scanner scanner3 = new Scanner(System.in);
    String password = scanner.nextLine();


    // Create file 
    FileWriter fstream = new FileWriter("username.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write(username + ":" + email + ":" + password);
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

But it keeps clearing the first line. Is there a way I can just get it to add a line each time instead of clearing the first one? If so can someone please help me. I am using repl.it for java.

  • 6
    Possible duplicate of [How to append text to an existing file in Java](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Lorelorelore Sep 10 '18 at 15:01

1 Answers1

2

You need to open File with append flag as true.

FileWriter fstream = new FileWriter("username.txt",true);
    BufferedWriter out = new BufferedWriter(fstream);
out.write("\n" + username + ":" + email + ":" + password);

This will ensure that, content in the file in appended. Also, "\n" will ensure that each line is printed on new line in file.

mukesh210
  • 2,792
  • 2
  • 19
  • 41