HW 6.5
package com.gmail.vhrushyn;
import java.io.File;
import java.util.Arrays;
public class MyFileMonitor implements Runnable {
private File file;
private File[] files;
private File[] temp;
public MyFileMonitor(File file) {
super();
this.file = file;
}
public MyFileMonitor() {
super();
// TODO Auto-generated constructor stub
}
private void Monitoring(File file) {
files = file.listFiles();
int c = 0;
if (temp == null) {
temp = Arrays.copyOf(files, files.length);
} else {
c = files.length - temp.length;
}
if (c == 0) {
} else if (c > 0) {
System.out.println("New file: '" + MyGetNameMore(files, temp) + "' was added");
} else if (c < 0) {
System.out.println("File: '" + MyGetNameLess(files, temp) + "' was removed");
}
temp = files;
}
private String MyGetNameMore(File[] files, File[] temp) {
String name = "";
for (int i = 0; i < files.length; i++) {
for (int j = 0; j < temp.length; j++) {
if (!temp[j].getName().equals(files[i].getName())) {
name = files[i].getName();
}
}
}
return name;
}
private String MyGetNameLess(File[] files, File[] temp) {
String name = "";
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < files.length; j++) {
if (!temp[i].getName().equals(files[j].getName())) {
name = temp[i].getName();
}
}
}
return name;
}
@Override
public void run() {
while (true) {
Monitoring(file);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
package com.gmail.vhrushyn;
import java.io.File;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("."); // folder address to monitoring
System.out.println("Start monitoring");
Thread t = new Thread(new MyFileMonitor(file));
t.start();
}
}