有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在此文件中覆盖

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

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

共 (1) 个答案

  1. # 1 楼答案

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

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