cn.asens.util.PropertyUtils Maven / Gradle / Ivy
package cn.asens.util;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Asens
*
* PropertyUtils should used in web application,the ROOT path is /WEB-INF/classes
* you should create property.properties under "/WEB-INF/classes/" path
* you can change the place and use getProperty(String location,String key)
* to getProperty from any where.
*
* use "=" between key and value
* use "#" to make it notAvailable
*
* location should like "/config/config.ini" means "/WEB-INFO/classes/config/config.ini"
*
* return null if file not exist|read Error|any Exception|key not exist
*
* 2017-07-14
*/
public class PropertyUtils {
/**
* get property of the key in specified location
* @param key use before "="
* @param location "/config/config.ini"-"/WEB-INFO/classes/config"
* @return the value of the key of the location
*/
public static String getProperty(String location, String key){
InputStream is=getLocationFile(location);
try {
return getConfigMap(is).get(key);
} catch (IOException e) {
return null;
}
}
private static InputStream getLocationFile(String location) {
InputStream is= Thread.currentThread().getContextClassLoader()
.getResourceAsStream(location);
if(is==null||location.startsWith("/")){
return Thread.currentThread().getContextClassLoader()
.getResourceAsStream(location.substring(1));
}
throw new IllegalStateException("file not found");
}
public static Map getConfigMap(InputStream is) throws IOException {
Map config=new LinkedHashMap();
List list=readFileAsList(is);
for(String line:list){
if(line.startsWith("#")) {
continue;
}
if(isWhiteSpace(line)) {
continue;
}
if(!line.contains("=")){
continue;
}
int fd = line.indexOf("=");
String key = line.substring(0, fd);
String value = line.substring(fd + 1);
config.put(key,value);
}
return config;
}
private static List readFileAsList(InputStream is) throws IOException {
List list=new ArrayList();
InputStreamReader isr=null;
BufferedReader br=null;
try{
isr=new InputStreamReader(is,"utf-8");
br=new BufferedReader(isr);
String str;
while ((str = br.readLine()) != null) {
list.add(str);
}
}catch (UnsupportedEncodingException ignored){
}finally {
if (is != null) {
is.close();
}
if (isr != null) {
isr.close();
}
if (br != null) {
br.close();
}
}
return list;
}
private static boolean isWhiteSpace(String line) {
return line.replace(" ", "").equals("");
}
}