如何将数据添加到文本文件中,而不是覆盖我在Java中的内容

-2 java file-io file

到目前为止这是我的代码,但它已经覆盖了我在文本文件中的内容.我想要的是将它添加到文本文件中的新行.

import java.io.*;
import java.util.Scanner;

public class Login{
  public static void main(String[] args) throws IOException {
    Scanner s1,s2;
    s1 = new Scanner(new FileInputStream("login.txt"));
    s2 = new Scanner(System.in);
    boolean loggedIn = false;
    String name,pword,n,p;
    System.out.println("Are you a new user? (Type y for yes or n for no)");
    String nU = s2.next();

    if (nU.equals("n"))
    {
    System.out.println("Enter username:");
    n=s2.next();
    System.out.println("Enter password:");
    p=s2.next();
    while(s1.hasNext()){
      name=s1.next();
      pword=s1.next();
      if(n.equals(name) && p.equals(pword)){
        System.out.println("You are logged in.");
        loggedIn = true;
        break;
      }
    }
    if(!loggedIn)
      System.out.println("Incorrect password or username.");
    }
    else if (nU.equals("y"))
    {
Run Code Online (Sandbox Code Playgroud)

这里是我的代码问题所在,因为这是将它写入文件的地方.

     PrintWriter out = new PrintWriter("login.txt"); 
     System.out.println("Enter username:");
     n=s2.next();
     System.out.println("Enter password:");
     p=s2.next();
     out.append(n);
     out.append(p);
     out.close();
     System.out.println("Account has been created and you are logged in.");
    }
    else
      System.out.println("Invalid response.");
Run Code Online (Sandbox Code Playgroud)

Kic*_*ski 11

它建议使用的链条 BufferedWriterFileWriter,关键的一点是FileWriter将追加字符串到当前文件中使用它的构造函数中的一个,通过增加让appaneding当true像去年放慢参数

new FileWriter("login.txt", true)        
Run Code Online (Sandbox Code Playgroud)

当我们用BufferedWriter对象包围它时为了更高效,如果你要写入文件的时间数,那么它将字符串缓存在大块中并将大块写入文件中,显然你可以节省很多写入文件的时间

注意:有可能不使用BuffredWriter,但建议使用它,因为它具有更好的性能和缓冲大块字符串并将其写入一次的能力

只是改变你的

PrintWriter out = new PrintWriter("login.txt"); 
Run Code Online (Sandbox Code Playgroud)

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
Run Code Online (Sandbox Code Playgroud)

例:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
    String data = "This content will append to the end of the file";
    File file = new File("login.txt");
    out.println(data);
} catch(IOException e) {
}
Run Code Online (Sandbox Code Playgroud)

没有使用就可以解决这个问题BufferedWriter,但是我提到的性能会很低.

例:

try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
    String data = "This content will append to the end of the file";
    File file = new File("login.txt");
    out.println(data);
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)