.xml正向反向取值(之四)
FileListener类:
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Enumeration;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.TimerTask;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;import org.kxml2.io.KXmlParser;import org.kxml2.kdom.Document;import org.kxml2.kdom.Element;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import com.%##.common.XMLParserHelper;/* * Class: FileListener * Description: 单个文件监听,如果文件已更新则自动重新加载 * Version: 1.0 * Author: Carson.Huang * Created on Dec 1, 2010 */public class FileListener extends TimerTask{private File file = null;private long lastModified = 0;private Properties prop = new Properties();private Element element = new Element();private boolean fileFlag = true; private Logger logger = Logger.getLogger(FileListener.class); //所有的枚举文件 private Map<String,EnumerateFile> enumerateFiles=new HashMap<String,EnumerateFile>(); //枚举文件 private List<String> enumPaths=new ArrayList<String>(); //当前的枚举文件名 private String currentEnumFilePath=""; FileListener(String filePath){//设置所有的枚举文件的信息filePath=setEnumInfo(filePath);if (filePath != null){this.file = new File(filePath);if (!file.isFile()){logger.error("The file[" + filePath + "] doesn't exist, please check it.");return;}if (this.file.getName().endsWith(".properties")){fileFlag = true;}else if (this.file.getName().endsWith(".xml")){fileFlag = false;}else{logger.info("nothing to do...");}}}public void run(){if (isFileUpdated() && fileFlag){ logger.info("The properties file[" + getPath() + "] was modified."); loadFile();}else if(isFileUpdated() && !fileFlag){StringBuffer sb=new StringBuffer();for(String s : enumerateFiles.keySet()){sb.append(enumerateFiles.get(s).getReLoadEnumFilePath()).append("\t"); }logger.info("The properties files[" + sb.toString() + "] was modified.");loadFile();}}private boolean isFileUpdated(){if(this.fileFlag){long lastUpdateTime = file.lastModified(); return lastUpdateTime > this.lastModified;}else{return EnumerateFile.checkFileIsModified(enumerateFiles);} }public void loadFile(){if (this.fileFlag) { loadProperties(); } else { for(String s : enumerateFiles.keySet()){ if(enumerateFiles.get(s).getReLoadEnumFilePath()!=null&&enumerateFiles.get(s).getReLoadEnumFilePath().length()>1){ currentEnumFilePath=s; loadXml(); } } }}