-4

I want to overwrite in this file but I cannot. It just store one time. I want to store data every time I input in it.

    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();
}
akash
  • 22,664
  • 11
  • 59
  • 87
  • 4
    Do you mean you want to *append*? It sounds like it *is* overwriting... – Jon Skeet Aug 26 '15 at 10:48
  • use the constructor with the boolean append parameter. Googling for "java open file for appending" I found this: http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – vefthym Aug 26 '15 at 10:50

1 Answers1

0

You can get the data of the old Employees from the file, and then concatenate the new Employee at the end.

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();
}
Kevin
  • 2,813
  • 3
  • 20
  • 30
chenchuk
  • 5,324
  • 4
  • 34
  • 41