public class ResourceHelper
{
private static final String FILE_PROTOCOL = "file://";
private ResourceHelper()
{
super();
}
/**
* Get resouce as stream
* @param strResourceName String
* @return InputStream
* @throws RollingPlanException
*/
public static InputStream getResourceAsStream(String strResourceName)
throws RollingPlanException
{
try
{
if (null == strResourceName)
{
return null;
}
//检查是不是本地文件协议
if (strResourceName.startsWith(FILE_PROTOCOL))
{
File file = new File(strResourceName.substring(FILE_PROTOCOL.length()));
if (file.exists())
{
return new java.io.FileInputStream(file);
}
else
{
return null;
}
}
String strNewResouce = strResourceName.startsWith("/") ? strResourceName.substring(1) : strResourceName;
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (null == stream)
{
stream = classLoader.getResourceAsStream(strNewResouce);
}
if (null == stream)
{
stream = Environment.class.getResourceAsStream(strResourceName);
}
if (null == stream)
{
stream = Environment.class.getClassLoader().getResourceAsStream(strNewResouce);
}
if (null == stream)
{
File file = new File(strResourceName);
if (file.exists())
{
stream = new java.io.FileInputStream(file);
}
}
if (null == stream)
{
throw new RollingPlanException("Can not found the resource named:" + strResourceName);
}
return stream;
}
catch (RollingPlanException excep)
{
throw excep;
}
catch (Exception excep)
{
throw new RollingPlanException(excep);
}
}
public static File getResourceFile(String strResource)
throws RollingPlanException
{
URL ret = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (null == ret)
{
ret = classLoader.getResource(strResource);
}
if (null == ret)
{
ret = Environment.class.getResource(strResource);
}
if (null == ret)
{
ret = Environment.class.getClassLoader().getResource(strResource);
}
if (null == ret)
{
File file = new File(strResource);
if (file.exists())
{
return file;
}
}
if (null == ret)
{
throw new RollingPlanException("Can not found the resource named:" + strResource);
}
else
{
return new File(ret.getFile());
}
}
}