package com.xiaopeng.trafficControl.util;
|
|
import java.io.*;
|
import java.lang.reflect.Method;
|
import java.net.URL;
|
|
/**
|
* 资源工具类
|
* @author binghuoliu
|
*
|
*/
|
public class ResourceUtil {
|
|
/**
|
* 读取classpath下的文件<br>
|
* 读取classpath下的文件 一般用于读取classpath下的配置文件,注意读取的配置文件路径是相对传入参数clazz的load入路径. 例:<br>
|
* ClassTest c1;//假设c1是从/usr/local/classpath/ 载入<br>
|
* ClassTest c2;//假设c2是从/home/classpath/ 载入<br>
|
* ............<br>
|
* loadConfigFile("a.xml",c1.class);//从/usr/local/classpath1/下寻找a.xml<br>
|
* loadConfigFile("a.xml",c2.class);//从/home/classpath/下寻找a.xml<br>
|
* @param resource 资源路径
|
* @param clazz
|
* @return InputStream 文件的inputstram,如果找不到则返回null
|
*/
|
@SuppressWarnings("unchecked")
|
public static InputStream loadConfigFile(String resource, Class clazz) {
|
ClassLoader classLoader = null;
|
try {
|
Method method = Thread.class.getMethod("getContextClassLoader");
|
classLoader = (ClassLoader) method.invoke(Thread.currentThread());
|
} catch (Exception e) {
|
throw new RuntimeException("loadConfigFile error: ", e);
|
}
|
if (classLoader == null) {
|
classLoader = clazz.getClassLoader();
|
}
|
try {
|
if (classLoader != null) {
|
URL url = classLoader.getResource(resource);
|
if (url == null) {
|
System.out.println("Can not find resource:" + resource);
|
return null;
|
}
|
if (url.toString().startsWith("jar:file:")) {
|
System.out.println("Get resource \"" + resource + "\" from jar:\t" + url.toString());
|
return clazz.getResourceAsStream(resource.startsWith("/") ? resource : "/" + resource);
|
} else {
|
System.out.println("Get resource \"" + resource + "\" from:\t" + url.toString());
|
return new FileInputStream(new File(url.toURI()));
|
}
|
}
|
} catch (Exception e) {
|
throw new RuntimeException("loadConfigFile error: ", e);
|
}
|
return null;
|
}
|
|
/**
|
* 释放资源(有异常抛出)
|
* @param closeable
|
* @throws IOException
|
*/
|
public static void close(Closeable closeable) throws IOException {
|
if (closeable != null) {
|
closeable.close();
|
}
|
}
|
|
/**
|
* 以优雅的形式释放资源(内部吃掉了异常)
|
* @param closeable
|
*/
|
public static void closeGracefully(Closeable closeable) {
|
if (closeable != null) {
|
try {
|
closeable.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
}
|