黑马程序员--用类加载器的方式管理资源和配置文件

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ---------------------- 

public class AA {

	public static void main(String[] args) throws IOException {
		/*
		 * 当config.properties放在工程目录根目录下时 可以直接用new
		 * FileInputStream("config.properties"),
		 * 否则使用绝对路径。不过开发时,不确定位置.所以开发时常用类加载器的方式,getClassLoader()
		 */
		 InputStream input = new FileInputStream(
		 "E:/Eclipse1/aaaa/src/com/sina/aaaa/config.properties");

		// 通过类加载器获取输入流,当config.properties文件放在哪一包中时,得在文件名前加上包名,如以下
		// com前不得加"/" 否则出错
		 InputStream input=AA.class.getClassLoader().getResourceAsStream("com/sina/aaaa/config.properties");
		
		
		//使用类字节码中自己的getResourceAsStream()获取输入流。
		//当源文件与config文件同一包时(因为使用的是类字节码的get方法,所以可以直接写config文件名)
		 InputStream input = AA.class.getResourceAsStream("config.properties");
		//当config文件在源文件子目录下时
		 InputStream input = AA.class.getResourceAsStream("rrrr/config.properties");
		// 当config文件与不同包时,注意com前的"/",表示这是个绝对路径
		 InputStream input = AA.class.getResourceAsStream("/com/sina/bbbb/config.properties");

		Properties pro = new Properties();
		pro.load(input);

		String str = pro.getProperty("name");
		System.out.println(str);
	}

}

 

更新:

java中类加载器主要有三个:BootStrap(加载器的内核,不是java类)ExtClassLoader(java类)AppClassLoader(java类)

关系图:

 

自定义类加载器:

public class Main {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		
		Class c=new Demo("123").findClass("Demo3");//Demo是自定义加载器 需继承系统加载器,此处的"123"为工程目录下的目录,"Demo3"为自定义加载器需要加载的类的类名,工程包下的Demo3类删除复制到"123"目录下. 使用findClass不要使用loadClass,见API            
		Date d=(Date) c.newInstance();//为什么不是Demo3,还是有点不懂,Demo3已经被加载了		       System.out.println(c.getClassLoader().getClass().getName());
		System.out.println(d);
	}

}
public class Demo3 extends Date{
	public String toString(){
		return "ni ge sb";
	}
	
}


public class Demo extends ClassLoader {

	private String pathName;

	@SuppressWarnings("resource")
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		pathName = pathName + "\\" + name + ".class";
		ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
		FileInputStream f = null;
		try {
			f = new FileInputStream(pathName);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		int len = 0;

		try {
			while ((len = f.read()) != -1) {
				byteArr.write(len);
			}
			byte[] by = byteArr.toByteArray();
			return defineClass(null, by, 0, by.length);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public Demo(String name) {
		this.pathName = name;
	}
}




---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值