Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

java - Saving input to a file is replaced when re-running

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.

question from:https://stackoverflow.com/questions/65906393/saving-input-to-a-file-is-replaced-when-re-running

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...