기분전환
1k
2015-02-17 09:34:30
4
7524

java watch 파일 감시 자바 코드



회사에서 쓸라고 테스트용으로 만들었는데 안쓰게 됐어요 


글쓰기 보니까 코드블럭 있는데 한번 올려보고 싶어서 올려봅니다


참고로 자바에 watch라는거 이번에 첨알았어요 ㅋㅋ 


* jdk7 이상만 됩니다


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());
		}
	}
}
7
4
  • 댓글 4

  • 기분전환
    1k
    2015-02-17 09:36:59

    코드 블럭 옵션에 라인넘보 표기 했는데 안나오네요..


    그리고 가로 길이가 짧아서 많이 깨져요 ㅠㅠ


    마우스 클릭하거나 올리면 가로 길이 길어지면 좋을거 같아요

    0
  • 믿음
    4k
    2015-02-17 09:39:00

    좋은 정보 감사합니다. ^^

    0
  • 일루미나타
    79
    2015-02-18 01:33:59

    좋은 정보네요 ^^

    0
  • 아졸려잘래
    516
    2015-02-23 11:49:09

    후.. 이거 java로 할려다 몰겠어서 C#으로 만들었던 기억이 있네요 ㅎ;;

    0
  • 로그인을 하시면 댓글을 등록할 수 있습니다.