<pre name="code" class="java">testU.java文件内容:
package testu;
import java.io.File;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jys1109
*/
public class testU implements Runnable {
private File[] roots = File.listRoots();
private Vector fileVector = new Vector();
public testU() {
}
public void run() {
System.out.println("check system start...");
while (true) {
File[] tempFile = File.listRoots();
boolean sign = false;
fileVector.removeAllElements();
if (tempFile.length > roots.length) {
for (int i = tempFile.length - 1; i >= 0; i--) {
sign = false;
for (int j = roots.length - 1; j >= 0; j--) {
if (tempFile[i].equals(roots[j])) {
sign = true;
}
}
if (sign == false) {
fileVector.add(tempFile[i]);
System.out.println("Enter:" + tempFile[i].toString());
}
}
roots = File.listRoots();//update roots
new FindFileThread(fileVector).start();//find files thread
} else {
for (int i = roots.length - 1; i >= 0; i--) {
sign = false;
for (int j = tempFile.length - 1; j >= 0; j--) {
if (tempFile[j].equals(roots[i])) {
sign = true;
}
}
if (sign == false) {
System.out.println("Quit:" + roots[i].toString());
}
}
roots = File.listRoots();//update roots
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(testU.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) {
new Thread(new testU()).start();
}
}
其中FindFileThread类为搜索文件的守护线程代码如下:
package testu;
import java.io.File;
import java.util.Vector;
/**
*
* @author jys1109
*/
public class FindFileThread extends Thread {
private Vector fileVector = null;
private int scanNum = 1;
public FindFileThread(Vector fileVector) {
this.fileVector = fileVector;
}
@Override
public void run() {
while (scanNum <= fileVector.size()) {
try {
System.out.println("search:"+ fileVector.elementAt(scanNum - 1).toString());
getFiles(fileVector.elementAt(scanNum - 1).toString());
scanNum++;
} catch (Exception e) {
System.out.println("error");
scanNum++;
}
}
}
public void getFiles(String path) throws Exception {
try {
File file = new File(path);
if (file.isDirectory()) {
File[] fList = file.listFiles();
for (int j = 0; j < fList.length; j++) {
if (fList[j].isDirectory()) {
getFiles(fList[j].getPath()); //recursion
}
if (fList[j].getName().endsWith(".java")) {
System.out.println(fList[j]);
}
}
}
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}