0

I'm trying to create something similar to a mail server. Now, I'm supposed to have a file called 'Credentials' that saves the email and password entered each time I run the client.

File Credentials = new File("Server\\Credentials.txt");
 try{
       if(Credentials.createNewFile()){
               System.out.println("Credentials created");
         }else {System.out.println("Credentials already exists");}

  }catch(Exception error){}

try (
      PrintWriter out = new PrintWriter(Credentials, "UTF-8")
    ) {
               out.println("Email: " + email);
               out.println("Password: " + password);
      } catch(IOException e) {
               e.printStackTrace();
      }

However, each time a client runs, it replaces the old email and password. Any idea how to make it continue to the next line without replacing? Thank you.

  • Fair, retracted the vote. You have to open your PrintWriter in append mode instead. Check the javadoc for its constructors, there should be one taking a `boolean` to indicate append instead o truncate mode. – Zabuzard Jan 26 '21 at 17:46
  • 1
    That said, the way you are interacting with your file is very old. Look into NIO, the new modern interface is much simpler and clearer to use. – Zabuzard Jan 26 '21 at 17:46
  • @Abra True, but NIO only really got very interesting starting with Java 7, especially 8 and also 9, due to `readAllLines`, `lines`, `readString`, `write`, `writeString` which covers almost all basic file interactons. Although thats also some years ago already, given that we are on 15 already :D – Zabuzard Jan 26 '21 at 17:59
  • @Zabuzard Ah, sorry lol. Our professor only taught us about data types, for loops,..etc and gave us a big assignment so all of my information is from googling and I'm sure some of them are old outdated questions. Thanks though! – NayaCruiser Jan 26 '21 at 18:17

1 Answers1

0

As previously mentioned you have to use the correct constructor, which will append your text instead of overriding.

But I would suggest to do it this way:

  public static void main(String[] args) {

    for (int i = 0; i < 10; i++) {
        doSomething("test" + i);
    }

}

static void doSomething(String text) {
    try (PrintWriter test = new PrintWriter(new BufferedWriter(new FileWriter("your path", true)))) {
        test.print(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Here are some further informations and different approaches for your issue: How to append text to an existing file in Java?