/** * Copyright 2011 Oliver Buchtala * * This file is part of ndogen. * * ndogen is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ndogen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ndogen. If not, see <http://www.gnu.org/licenses/>. */ package org.ndogen.watch; import java.io.File; import java.io.IOException; public class FileWatcher implements Runnable { long lastModified; String lastHash; final static long refreshInterval = 1000; private File file; private final Runnable runner; boolean running; public FileWatcher(String filePath, Runnable runner) { this.runner = runner; file = new File(filePath); } @Override public void run() { this.running = true; while(running) { if(file.lastModified() != lastModified) { String fileHash = ""; try { fileHash = FileUtils.getFileHash(file); if(!fileHash.equals(lastHash)) { // Note: these three actions are not atomar // so it may happen that the file changes while we // process it // to take the modification info before processing // is the conservative strategy lastModified = file.lastModified(); lastHash = fileHash; this.runner.run(); } } catch (IOException e) { e.printStackTrace(); } } try { Thread.sleep(refreshInterval); } catch (InterruptedException e) { } } } }