Java使用多线程监控文件改动,并重新载入资源。

 最近做的一个项目用到了很多配置文件,当一个文件改动之后,项目必须重启才可以使改动生效,所以利用空余时间写了这么个小程序,希望大神指点,也希望能给看到的朋友帮助。废话不多说,开始。

程序的思路:使用多线程每个一定时间检查配置文件的最后修改日期,如果和程序中保存的不一致,那就重新读取这些资源。

package com.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class FileReload {
	
	private Properties properties;
	private String filePath;
	
	
	public FileReload(String filePath) {
		super();
		this.filePath = filePath;
	}


	public String getAge() {
		return properties.getProperty("age");
	}


	public String getName() {
		return properties.getProperty("name");
	}


	public void startCheck(String fileName){
		File file = new File(fileName);
		startCheck(file);
	}
	
	//初始化代码,将数据读取到内存中,这里面是我的实现,可以根据不同的需求更改实现
	public void init(){
		if(properties == null)
			properties = new Properties();
		InputStream in = null;
		try {
			in = new FileInputStream(new File(this.filePath));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if(in == null)
			in = this.getClass().getResourceAsStream(this.filePath);
		if(in == null)
			in = this.getClass().getClassLoader().getResourceAsStream(this.filePath);
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//开始监控
		startCheck(this.filePath);
	}
	
	//开始监控
	public void startCheck(final File file){
		Runnable checkThread = new Runnable() {
			private long lastModified;
			@Override
			public void run() {
				long lastModified = file.lastModified();
				if(this.lastModified != lastModified){
					this.lastModified = lastModified;
					init();
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		
		Thread thread = new Thread(checkThread);
		thread.start();
	}
	
	public static void main(String[] args) {
		String filePath = "d://test.properties";
		final FileReload reload = new FileReload(filePath);
		reload.init();
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println(reload.getAge() + "-----" + reload.getName());
			}
		}, new Date(), 1000);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值