读取.properties中的IPlist技巧

public class IpConfig {
	private static final Logger logger = LoggerFactory.getLogger(IpConfig.class);
	
	private static boolean isReady = false;
	
	private static IpConfig instanced = new IpConfig();	
	public static IpConfig getInstanced() {
		return instanced; 
	}
	
	private List<String> ip;
	long startTime;
	long lastModifiedTime;
	
	private IpConfig() {
		
		if (!isReady){
			isReady = true;
			String path = this.getClass().getResource(PropertiesUtil.getValue("ip.white.list.path")).getFile();
			initConfiguration(path);						
			startTime = System.currentTimeMillis();
		}
	}

	public void initConfiguration(String path) {
		File file = new File(path);
		
		if (!file.exists()) {
			logger.debug("file is null");
			return;
		}
		
		lastModifiedTime = file.lastModified();

		BufferedReader bf = null;
		FileReader fileReader = null;
		List<String> ipList = new ArrayList<String>();
		try {
			fileReader = new FileReader(file);
			bf = new BufferedReader(fileReader); 
			
			String line = null;
			while ((line = bf.readLine()) != null) {
				ipList.add(line.trim().replace(" ", ""));
			}
			
			if (ipList.size() > 0) {
				ip = ipList;
			}

		} catch (FileNotFoundException e) {
			logger.error("action:config;error message:" + e.getMessage());
		} catch (IOException e) {
			logger.error("action:config;error message:" + e.getMessage());
		} finally {
			try {
				closeReadFile(bf, fileReader);
			} catch (IOException e) {
				logger.error("action:config;error message:" + e.getMessage());
			}
		}
		
	}

	protected void closeReadFile(BufferedReader bufferedReader, FileReader fileReader) throws IOException{
		if (bufferedReader!=null){
			bufferedReader.close();
		}
		if (fileReader!=null){
			fileReader.close();
		}
	}
	
	public List<String> getIpList() {
		long endTime = System.currentTimeMillis();
		long readTime = endTime - startTime;
		
		if (readTime > Long.parseLong(PropertiesUtil.getValue("ip.timeout.time")) * 1000){
			String path = this.getClass().getResource(PropertiesUtil.getValue("ip.white.list.path")).getFile();
			File file = new File(path);
			long lastRead = file.lastModified();
			//If file had been modified, need to init again
			if (lastModifiedTime != lastRead) {
				initConfiguration(path);				
			} 
			startTime = endTime;
			
		}
		if (ip != null && ip.size() > 0) {
			return ip;
		}
		return null;
	}

}

猜你喜欢

转载自jameskaron.iteye.com/blog/2387560