通过多线程我们可以监视一个目录,一旦目录里出现新的文件,我们就将该文件转移至指定的目录中去:
下面我们来看看这些具体实现:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 创建一个线程,监视某个目录,一旦目录里出现新的文件,就将文件转移到指定的目录里去
*
* @author HP
*/
public class FileListener extends Thread {
private File file1;
private File file2;
public FileListener(File file1, File file2) {
this.file1 = file1;
this.file2 = file2;
}
public void copy(File file1, File file2) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bow = null;
try {
bis = new BufferedInputStream(new FileInputStream(file1));
File target = new File(file2, file1.getName());
bow = new BufferedOutputStream(new FileOutputStream(target));
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bow.write(b, 0, len);
}
} finally {
if (bow != null)
bow.close();
if (bis != null)
bis.close();
}
}
@Override
public void run() {
File[] files1 = file1.listFiles();
int len1 = files1.length;
while (true) {
File[] files2 = file1.listFiles();
int len2 = files2.length;
if (len1 != len2) {
for (File file : files2) {
for (File file1 : files1) {
if (file.exists()) {
break;
} else {
try {
copy(file, file2);
file.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
public static void main(String[] args) {
File f1 = new File("F:\\sb");
File f2 = new File("F:\\新建文件夹\\新建文件夹2");
FileListener fls = new FileListener(f1, f2);
new Thread(fls).start();
}
}