为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

忽然笑 2021-09-12 16:08:43
我目前拥有的是这个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。
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

您需要打开带有附加标志的文件为真。


FileWriter fstream = new FileWriter("username.txt",true);

    BufferedWriter out = new BufferedWriter(fstream);

out.write("\n" + username + ":" + email + ":" + password);

这将确保附加文件中的内容。此外,“\n”将确保每一行都打印在文件的新行上。


查看完整回答
反对 回复 2021-09-12
  • 1 回答
  • 0 关注
  • 156 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信