http://blog.csdn.net/wan368500/article/details/8215668
ServletContext.getResource()
如果使用ServletContext.getResource(path)方法,路径必须以"/"开始,路径被解释成相对于ContextRoot的路径,此处载入文件的方法和ClassLoader不同,举例"/WEB-INF/web.xml","/download/WebExAgent.rar"
ServletContext.class.getResource("/WEB-INF/classes");
2. 使用ClassLoader
/**
* 因为有3种方法得到ClassLoader,对应有如下3种方法读取文件
* 使用的路径是相对于这个ClassLoader的那个点的相对路径,此处只能使用相对路径
*/
InputStream is = null;
is = this.getClass().getClassLoader().getResourceAsStream(
"com/rain/config/sys.properties"); //方法1
//is = Thread.currentThread().getContextClassLoader().getResourceAsStream(
"com/rain/config/sys.properties"); //方法2
//is = ClassLoader.getSystemResourceAsStream("com/rain/config/sys.properties"); //方法3
package com.zving.preloader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import com.zving.framework.thirdparty.commons.io.ByteArrayOutputStream;
public class TestClassLoader extends ClassLoader {
// 定义文件所在目录
private static final String DEAFAULTDIR = "E:\\MyProjects\\workspace\\TestConsole\\bin\\";
public Class<?> findClass(String name)
throws ClassNotFoundException {
byte[] b = null;
try {
b = loadClassData(GetClassName(name));
} catch (Exception e) {
e.printStackTrace();
}
return defineClass(name, b, 0, b.length);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (name.startsWith("java.")) {
try {
return super.loadClass(name, false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
byte[] b = null;
try {
b = loadClassData(GetClassName(name));
} catch (Exception e) {
e.printStackTrace();
}
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String filepath)
throws Exception {
int n = 0;
BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(filepath)));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((n = br.read()) != -1) {
bos.write(n);
}
br.close();
return bos.toByteArray();
}
public static String GetClassName(String name) {
System.out.println(DEAFAULTDIR + name.replace('.', '/') + ".class");
return DEAFAULTDIR + name.replace('.', '/') + ".class";
}
}