猿问

如何将字符串存储在 .txt 文件中,同时不清除该文件中已有的内容 java

我目前拥有的是这个


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());

    }

  }

}

但它一直在清除第一行。有没有办法让它每次都添加一行而不是清除第一行?如果可以,请有人帮助我。我正在为 java 使用 repl.it。


忽然笑
浏览 157回答 1
1回答

慕娘9325324

您需要打开带有附加标志的文件为真。FileWriter fstream = new FileWriter("username.txt",true);    BufferedWriter out = new BufferedWriter(fstream);out.write("\n" + username + ":" + email + ":" + password);这将确保附加文件中的内容。此外,“\n”将确保每一行都打印在文件的新行上。
随时随地看视频慕课网APP

相关分类

Java
我要回答