多线程实现文件修改监听转移

通过多线程我们可以监视一个目录,一旦目录里出现新的文件,我们就将该文件转移至指定的目录中去:
下面我们来看看这些具体实现:

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();

	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值