<< Using Multiple "buttons" Elements in IE6 | 首页 | js window.onload 加载多个函数和追加函数 - 唔愛吃蘋果 - 博客园 >>

Auto refreshing properties from property files | Entelligentsia Blog

一个自动重新加载配置文件修改的Properties类:
 
 
class AutoRefreshingProperties extends Properties{
    private long LAST_LOADED = System.currentTimeMillis();
    private List listeners = Collections.synchronizedList(new ArrayList());
    public AutoRefreshingProperties(String absolutePathToPriopertiesFile) throws IOException{
        this(null, absolutePathToPriopertiesFile);
    }
    public AutoRefreshingProperties(Properties defaults, String absolutePathToPriopertiesFile) throws IOException{
        super(defaults);
        load(absolutePathToPriopertiesFile);
    }
    public AutoRefreshingProperties removeListener(FileChangeListener listener){
        listeners.remove(listener);
        return this;
    }
    public AutoRefreshingProperties addListener(FileChangeListener listener){
        listeners.add(listener);
        return this;
    }
    public synchronized void load(String absoluteFilePath) throws IOException {
        InputStream is = new FileInputStream(new File(absoluteFilePath));
        this.load(is);
        LAST_LOADED = System.currentTimeMillis();
        keepUpdated(absoluteFilePath);
    }
    abstract class FileWatcher implements Runnable{}
    private void keepUpdated(final String absoluteFilePath){
        Executors.newSingleThreadExecutor().submit(
                new FileWatcher(){
                    @Override
                    public void run() {
                        try {
                            while(true){
                                if (new File(absoluteFilePath).lastModified() &gt; LAST_LOADED){
                                    InputStream is =  new FileInputStream(new File(absoluteFilePath));
                                    load(is);
                                    LAST_LOADED = System.currentTimeMillis();
                                    notifyListeners();
                                }
                                Thread.yield();
                                Thread.sleep(2000);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        );
    }
    private void notifyListeners(){
        final Properties properties = new Properties(this);
        for (FileChangeListener aListener : listeners){
            aListener.notifyFileChanged(properties);
        }
    }
}

阅读全文……




发表评论 发送引用通报