I am trying to create a Text Editor with an "Auto-Save" feature. This means that whenever the user makes any changes to the current text (e.g. appends or deletes letters, words, lines, etc) then that change should be immediately applied to the text file as well.
I use a "TextArea" control from Javafx to detect any changes in the text. Also, I use a BufferedWriter to write the new text to the file, from scratch, whenever a change is detected. However that doesn't seem correct to me, because the BufferedWriter will have to re-write all the text from scratch. This will cause performances issues if the text is too big.
Does anyone have a better idea of how to Implement this? Thanks in advance.
The trick is to use a timer, and write the update only if the document has been modified.
The example given works with Swing components, but can be adapted to other frameworks
boolean dirtyFlag = false; // set true if the document is altered
DocumentListener dl = new DocumentListener() { ... // implement all methods and set dirtyFlag = true in each
TimerTask task = new TimerTask() {
public void run() {
//save the file
}
}
Timer t = new Timer();
t.scheduleAtFixeRate(task, ..., ...);