com.github.linushp.commons.PropertiesUtils Maven / Gradle / Ivy
package com.github.linushp.commons;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertiesUtils {
private static final String CLASSPATH = "classpath:";
private static final Map propertiesMap = new HashMap<>();
private static Properties loadProperties(String fileName) throws IOException {
InputStream inStream = null;
if (fileName.startsWith("./") || fileName.startsWith("../") || fileName.startsWith("/")) {
File file = new File(fileName);
inStream = new FileInputStream(file);
} else if (fileName.length() > 2 && fileName.charAt(1) == ':') {
//for windows : C:\\
File file = new File(fileName);
inStream = new FileInputStream(file);
} else if (fileName.startsWith("~")) {
String userHome = System.getProperty("user.home");
String filePath = fileName.replaceFirst("~", userHome);
File file = new File(filePath);
inStream = new FileInputStream(file);
} else if (fileName.startsWith(CLASSPATH)) {
String filePath = fileName.substring(CLASSPATH.length());
filePath = (filePath.charAt(0) == '/' ? filePath.substring(1) : filePath);
inStream = PropertiesUtils.class.getClassLoader().getResourceAsStream(filePath);
} else {
inStream = PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName);
}
Properties properties = new Properties();
properties.load(inStream);
IOUtils.tryClose(inStream);
//放入缓存
propertiesMap.put(fileName, properties);
return properties;
}
public static Properties getProperties(String fileName) throws IOException {
Properties p = propertiesMap.get(fileName);
if (p == null) {
p = loadProperties(fileName);
}
return p;
}
public static Map toMap(Properties p) {
Map map = new HashMap<>();
if (p == null) {
return map;
}
Set> entrySet = p.entrySet();
for (Map.Entry