I wrote a Java program which watches a directory for changes. I keep a list of files (String[]) and at every x seconds I get a new list and compare them to find which files were added and which ones were removed.
The problem is that if I rename a file, it would appear as a removal of a file with the old name and then as an addition of a file with the new name.
What could I do to keep track of name changes?
EDIT: I would like to find a solution for Java 6. Code:
public void run() {
int ok;
while(true) {
// verify if modified from last check
if(modified != file.lastModified()) {
Date d = new Date();
list = file.list();
// look for new files
for(String x : list) {
ok = 0;
for(String y : old) {
if(x.equals(y)) {
ok = 1;
}
}
if(ok == 0) {
display.setText(display.getText() + "Created file " + x + " at " + d.toString() + "\n");
}
}
// looking for old files
for(String x : old) {
ok = 0;
for(String y : list) {
if(x.equals(y)) {
ok = 1;
}
}
if(ok == 0) {
display.setText(display.getText() + "Deleted file " + x + " at " + d.toString() + "\n");
}
}
}
old = file.list();
modified = file.lastModified();
try {
Thread.sleep(f * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Also, in this code, if I want to write old = list (to keep the last list), i get a NullPointerException
at line for(String y : old)
. Why?