⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 detectthread.java

📁 java编写的监控一个文件夹里面有没有新的excel文件放入
💻 JAVA
字号:
/**
 * 
 */
package com.justin.detect;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.justin.log.*;
import com.justin.config.*;
import com.justin.util.*;

/**
 * @author Justin
 * 
 */
public class DetectThread extends Thread {
	// 监测目标文件夹
	private File detectDir;

	// 监测器
	private Detector detector;

	// 日志
	private LogServer log;

	// 配置文件管理器
	private ConfigManager config;

	// 监测间隔
	private int detectInterval;

	public DetectThread() {
		log = LogServer.getInstance();
		config = ConfigManager.getInstance();
		detectDir = new File(config.getDetectDir());
		detector = new Detector(detectDir, config.getDetectExt());
		detectInterval = config.getDetectInterval();
	}

	public void run() {
		// 让界面线程先初始化
		try {
			Thread.sleep(3000);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		boolean isDir = detector.checkDir();
		if (isDir) {
			log.showMessage("开始监控数据……");	
			while (true) {
				if (detector.detect()) {
					String[] fileNames = detector.getNewFileNames();
					log.showMessage("<-- 监测到新数据 于" + getCurTime() + " -->");
					for(int i = 0; i < fileNames.length; i++ ){
						log.showMessage(fileNames[i]);
						detector.markFoundFile(fileNames[i]);						
					}		
					log.showMessage("<-- 开始进行数据备份 于" + getCurTime()
							+ " -->");
					for(int i= 0; i < fileNames.length; i++ ){						
						try {
							String sourcePath = getSourcePath(fileNames[i]);
							String backupPath = getBackupPath(fileNames[i]);
							FileCopier.copy(sourcePath, backupPath);
							log.showMessage("<-- "+ fileNames[i] + "备份成功 -->");
						} catch (IOException ex) {
							System.err.println(ex);
						}
					}
					
// 在此应触发找到新文件的处理事件,待写
				}
				try {
					Thread.sleep(detectInterval);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		} else {
			log.showMessage("监测文件夹不存在");
		}
	}

	private String getCurTime() {
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(date);
	}

	private String getSourcePath(String fileName) {
		return detectDir.getPath() + "\\"
				+ fileName.replaceFirst(config.getDetectExt(), "found");
	}

	private String getBackupPath(String fileName) {
		//获取备份时间戳
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy_MM_dd_HH_mm_ss");
		String backupTime = dateFormat.format(date);
		//
		int index = fileName.lastIndexOf(".");
		String preName = fileName.substring(0, index) + backupTime;
		String backupPath = config.getBackupDir() + "\\" + preName + ".xls";
		
		return backupPath;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -