项目中用到的许多第三方访问路径都是在.proterties文件中配置的,感觉读取方法的这一部分,还是适合我这种菜鸟记一下的,方便自己以后查看:
路径=PropertiesLoader.getInstance().getProperty("CDNSERVERURL", true);
PropertiesLoader类如下:
package com.geo.dsp.ioperator.util;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;
public class PropertiesLoader {
private static PropertiesLoader instance = null;
private static Properties p = null;
private static String absolutePath;
private PropertiesLoader() {
p = new Properties(); //Properties以键值对的形式保存properites文件信息
URL url = Thread.currentThread().getContextClassLoader().getResource("ApplicationResources.properties");//获取资源的绝对路径的方式之一
if (url == null) {
url = Thread.currentThread().getContextClassLoader().getResource("ApplicationResources_zh_CN.properties");
if (url == null)
throw new IllegalStateException("ApplicationResources.properties");
}
// Load settings
try {
p.load(url.openStream());//url.openStream():打开到此 URL
的连接并返回一个用于从该连接读入的 InputStream
。 p.load(): 从输入流中读取属性列表(键和元素对)。
} catch (IOException e) {
throw new RuntimeException("Could not load ApplicationResources.properties:" + e);
}
absolutePath = getWebInfPath(); //处理后得到绝对路径,在下面
}
public static PropertiesLoader getInstance() {
if (instance == null) {
instance = new PropertiesLoader();
}
return instance;
}
public static String getWebRootPath() {
return absolutePath;
}
public static String getProperty(String key, boolean absolute) {
String s = p.getProperty(key);
if (s.startsWith("{$}")) {
if (absolute)
s = StringUtils.replace(s, "{$}", absolutePath);
else
s = StringUtils.replace(s, "{$}", "/");
}
return s;
}
private String getWebInfPath() {
Properties prop = System.getProperties(); //用于获取系统资源
String os = prop.getProperty("os.name");//得到系统类型(windows或者linux等..)
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
String path = url.toString();
int index = path.indexOf("WEB-INF");
if (index == -1) {
index = path.indexOf("classes");
}
if (index == -1) {
index = path.indexOf("bin");
}
path = path.substring(0, index);
if (path.startsWith("zip")) {//当class文件在war中时,此时返回zip:D:/...这样的路径
path = path.substring(4);
} else if (path.startsWith("file")) {//当class文件在class文件中时,此时返回file:/D:/...这样的路径
path = path.substring(6);
} else if (path.startsWith("jar")) {//当class文件在jar文件里面时,此时返回jar:file:/D:/...这样的路径
path = path.substring(10);
}
try {
path = URLDecoder.decode(path, "UTF-8");
if (!(os.startsWith("win") || os.startsWith("Win"))) {
path = "/" + path;
// System.out.println("nnnrootpath:"+path);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
}