`

Classloader getResourceAsStream深入

阅读更多
先写个简单的类
public class Helper {

	public static void main(String []args){
		try {
			new Helper().read("com/test/one/Foo.class");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void read(String f) throws IOException{
		InputStream in=getClass().getClassLoader().getResourceAsStream((f));


		int len=0;
		OutputStream out=new FileOutputStream("c:\\ooy.class");
		byte b[]=new byte[1023];
		while((len=in.read(b))!=-1){
			out.write(b);
		}
	}
}


他的路径是以当前类文件的地址搜索的
他和getResource()一样的搜索顺序!!
此方法首先搜索资源的父类加载器;如果父类加载器为 null,则搜索的路径就是虚拟机的内置类加载器的路径。如果搜索失败,则此方法将调用 findResource(String) 来查找资源。
如果你改为 read("");
他会自动加载你工程下 default package下类的名字 

你输入到txt 就会发现 类名!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics