码迷,mamicode.com
首页 > 其他好文 > 详细

比较二个文件的最后修改时间FileListener

时间:2015-08-15 18:12:23      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

public class FileListener {
    public static void main(String[] args) {
        FileListener fileListener = new FileListener();
        fileListener.timer = new Timer(true);
        fileListener.start();
    }

    private Timer timer;

    private long currentTime = -1;

    private long lastModifiedTime = -1;

    private long times = 1;

    private long pollingInterval = 1000 * times;

    private String filePath = "c:\\test.txt";

    public FileListener() {
        File file = new File(filePath);
        lastModifiedTime = file.lastModified();
        currentTime = lastModifiedTime;
    }

    public void start() {
        timer.schedule(new FileMonitor(), 0, pollingInterval);

        while (true) {
            try {
                int ch = System.in.read();
                System.out.println("ch=" + ch);
                if (ch - ‘c‘ == 0) {
                    System.out.println("quit");
                    timer.cancel();
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class FileMonitor extends TimerTask {
        public void run() {
            File file = new File(filePath);
            lastModifiedTime = file.exists() ? file.lastModified() : -1;
            if (currentTime != lastModifiedTime) {//1439540671443
                String string = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS")
                        .format(lastModifiedTime);//1439540994156
                System.out.println("File changed At:" + string);
                currentTime = lastModifiedTime;
            }
        }
    }


}

 

比较二个文件的最后修改时间FileListener

标签:

原文地址:http://www.cnblogs.com/alamps/p/4732748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!