I'm a newbie in Java and I'm writing a online classroom app and I need to write a code for taking attendance when takeAttendance_sbm button is clicked. When one of them enters their name for attendance it saves the name to the txt file but when the other one enters their name, the first name gets deleted and doesn't show.
Code for the server
if(e.getSource() == takeAttendance_sbm) {
try {
String input = JOptionPane.showInputDialog("Attendance ");
System.out.println(input);
fw = new FileWriter(new File("mytextfile.txt"));
fw.write(input);
fw.write(System.lineSeparator());
fw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Code for the client
if(e.getSource() == takeAttendance_sbm) {
move_flag = true;
try {
String input1 = JOptionPane.showInputDialog("Attendance ");
System.out.println(input1);
fw = new FileWriter(new File("mytextfile.txt"));
fw.write(input1);
fw.write(System.lineSeparator());
fw.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
You need to open the FileWriter in append mode by passing the boolean literal true as the second parameter to the constructor:
new FileWriter(new File("textfile.txt"), true);
This will write text to the end of the existing file rather than replacing what was originally in the file.