[펌]JAVA 화일 감시 프로그램 만들기.

일을 하다보면 특정 디렉토리를 감시하여 특정 조건이 되면

존재 하는 화일을 처리 하는 프로그램이 필요 할때가 있다.

 

보통은 C/C++로 작업 하는데 어찌다 보니 보게된 블로그에서 어떤 분이 JAVA로 만들어 놓은게 있어서

갈무리 한다.

 

 

http://okky.kr/article/272376

 

Main.java

public class Main {
	// file moved original
	public static final String ORIGINAL_PATH = "D:\DEV\tempFile\javaTemp1";
	// file moved backup
	public static final String COPIED_PATH = "D:\DEV\tempFile\javaTemp2";
	// watching folder pattern
	public static final String PATTERN_MATCH = "([0-9]+)-([0-9]+)-([0-9]+)-(220)-(17420|6130)";
	// file recovery day
	public static final int INTERVAL = 7;
	// prohibited hour ( 0~24 Calendar.HOUR_OF_DAY )
	public static final int PROHIBITED_TIME_START = 2;
	public static final int PROHIBITED_TIME_END = 7;



	public static void main(String[] args) {

		WatchAgent w = new WatchAgent();
		try {
			// watch agent
			w.start();

			// file scheduler

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}



WatchAgent.java

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.File;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WatchAgent {

	public void start() throws Exception {
		ExecutorService service = Executors.newCachedThreadPool();
		final FileSystem fs = FileSystems.getDefault();
		final WatchService ws = fs.newWatchService();
		final Map<WatchKey, Path> keys = new ConcurrentHashMap<>();

		reg(fs.getPath(Main.ORIGINAL_PATH), keys, ws);

		service.submit(new Runnable() {
			@Override
			public void run() {

				System.out.println("WATCH START");
				while (Thread.interrupted() == false) {
					WatchKey key;
					try {
						key = ws.poll(10, TimeUnit.MILLISECONDS);
					} catch (InterruptedException | ClosedWatchServiceException e) {
						break;
					}
					if (key != null) {
						Path path = keys.get(key);
						for (WatchEvent<?> i : key.pollEvents()) {
							WatchEvent<Path> event = cast(i);
							WatchEvent.Kind<Path> kind = event.kind();
							Path name = event.context();
							Path child = path.resolve(name);

							String[] pathName = child.getFileName().toString().split("\\");
							String folderName = pathName[pathName.length - 1];
							System.out.println(folderName);
							if (folderName.matches(Main.PATTERN_MATCH)) {
								Calendar c = Calendar.getInstance();
								c.setTime(new Date());
								int nowHour = c.get(Calendar.HOUR_OF_DAY);
								System.out.printf("%s: %s %s%n", kind.name(), path, child);
								if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
									if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
										try {
											walk(child, keys, ws);
										} catch (IOException e) {
											e.printStackTrace();
										}
									}
								}
								if (nowHour >= Main.PROHIBITED_TIME_START && nowHour <= Main.PROHIBITED_TIME_END) {
									// do not move
								} else {
									try {
										File s = new File(path.toString() + File.separator + folderName);
										File d = new File(Main.COPIED_PATH + File.separator + folderName);
										FileMove.copyFolder(s, d);
									} catch (IOException e) {
										e.printStackTrace();
									} catch (SQLException e) {
										e.printStackTrace();
									}
								}
							} else {
								continue;
							}
						}
						if (key.reset() == false) {
							System.out.printf("%s is invalid %n", key);
							keys.remove(key);
							if (keys.isEmpty()) {
								break;
							}
						}
					}
				}
				System.out.println("END");
			}
		});
	}

	static void walk(Path root, final Map<WatchKey, Path> keys, final WatchService ws) throws IOException {
		Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
				reg(dir, keys, ws);
				return super.preVisitDirectory(dir, attrs);
			}
		});
	}

	static void reg(Path dir, Map<WatchKey, Path> keys, WatchService ws) throws IOException {
		WatchKey key = dir.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
		keys.put(key, dir);
	}

	@SuppressWarnings("unchecked")
	static <T> WatchEvent<T> cast(WatchEvent<?> event) {
		return (WatchEvent<T>) event;
	}
}



JDBCCon.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCCon {
	public Connection conn;
	private PreparedStatement pstmt;
	public static JDBCCon db;

	private JDBCCon() {
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "drivername";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			Class.forName(driver).newInstance();
			this.conn = (Connection) DriverManager.getConnection(url + dbName, userName, password);
		} catch (Exception sqle) {
			sqle.printStackTrace();
		}
	}

	public static synchronized JDBCCon getDbCon() {
		if (db == null) {
			db = new JDBCCon();
		}
		return db;

	}

	public void insert(String... parameter) throws SQLException {
		StringBuilder sb = new StringBuilder();
		sb.append("INSERT INTO test111 ");
		sb.append(" (test, test1, test2 ) ");
		sb.append("VALUES ");
		sb.append("(");
		for (@SuppressWarnings("unused") String p : parameter) {
			sb.append("?,");
		}
		sb.append(")");
		String query = sb.toString().replaceAll(",\)$", ")");

		pstmt = db.conn.prepareStatement(query);
		int count = 1;
		for (String p : parameter) {
			pstmt.setString(count++, p);
		}

		pstmt.executeUpdate();
	}


}



FileMove.java

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;

public class FileMove {

	public static void copyFolder(File src, File dest) throws IOException, SQLException {
		JDBCCon db = JDBCCon.getDbCon();

		if (src.isDirectory()) {
			if (!dest.exists()) {
				dest.mkdir();
				System.out.println("Directory copied from " + src + "  to " + dest);
			}
			String files[] = src.list();
			for (String file : files) {
				File srcFile = new File(src, file);
				File destFile = new File(dest, file);
				copyFolder(srcFile, destFile);
			}
		} else {
			FileSystem fs = FileSystems.getDefault();
			Path srcPath = fs.getPath(src.toString());
			Path destPath = fs.getPath(dest.toString());
			Files.move(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);

			db.insert("Y", srcPath.toString(), destPath.toString());
		}
	}
}