Java 如何在此文件中覆盖

Java 如何在此文件中覆盖,java,file,Java,File,我想覆盖此文件,但无法覆盖。它只储存一次。我想在每次输入数据时存储数据 int i = 0; while (i != 1) { int choice; System.out.println("1-show employee"); System.out.println("2-add employee"); System.out.println("3-remove employee"); System.o

我想覆盖此文件,但无法覆盖。它只储存一次。我想在每次输入数据时存储数据

    int i = 0;
    while (i != 1) {
        int choice;
        System.out.println("1-show employee");
        System.out.println("2-add employee");
        System.out.println("3-remove employee");
        System.out.println("   Enter Your Choice   ");
        Scanner s = new Scanner(System.in);
        choice = s.nextInt();
        switch (choice) {
            case 1:
                String z = showEmployee();
                System.out.println(z);
                break;
            case 2:
                String em;
                Scanner v = new Scanner(System.in);
                em = v.nextLine();
                addEmployee(em);
                System.out.println("Employee added");
                break;
            default:
                System.out.println("wrong ");
                break;
        }
        System.out.println("Continue=0");
        System.out.println("Exit=1");
        i = s.nextInt();
    }
}
public static void addEmployee(String n) throws FileNotFoundException, IOException {
    DataOutputStream f1 = new DataOutputStream(new FileOutputStream("E:\\test.txt"));
    f1.writeUTF(n);
    f1.close();
}
public static String showEmployee() throws FileNotFoundException, IOException {
    DataInputStream f1 = new DataInputStream(new FileInputStream("E:\\test.txt"));
    return f1.readUTF();
}

您可以从文件中获取旧员工的数据,然后在末尾连接新员工

public static void addEmployee(String n) throws FileNotFoundException, IOException {
    String oldData = showEmployee();
    DataOutputStream f1 = new DataOutputStream(new FileOutputStream("E:\\test.txt"));
    f1.writeUTF(oldData + "\n" + n);
    f1.close();
}

你的意思是你想追加吗?听起来像是在覆盖…使用带有布尔追加参数的构造函数。在谷歌上搜索“java open file for appending”,我发现: