---------------------- 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