最近做一些小的例子程序,需要读取配置文件,但对如下两种方法的使用不是很清楚,希望xdjm们帮解释下两者的区别//是包的路径,下面方有School.XML文件String configPath="/com/baijw/bean/config";第一种方式:
InputStream input = this.getClass().getResourceAsStream(configPath + "School.xml");如果将configPath的第一个“/”去掉,input就为null,为什么?,加上可以获取输入流
第二种方式:
InputStream input2 = this.getClass().getClassLoader().getResourceAsStream(configPath + "School.xml");
不管去不去掉第一个“/”,好像都可以拿到输入流到底如果我要读取配置文件,路径该怎么写合适?
InputStream input = this.getClass().getResourceAsStream(configPath + "School.xml");如果将configPath的第一个“/”去掉,input就为null,为什么?,加上可以获取输入流
第二种方式:
InputStream input2 = this.getClass().getClassLoader().getResourceAsStream(configPath + "School.xml");
不管去不去掉第一个“/”,好像都可以拿到输入流到底如果我要读取配置文件,路径该怎么写合适?
如果没记错的话,你的第一种写法表示 “configPath + "School.xml"” 相对你当前类所在的包。所以不能去掉 / 去掉了则被解释为 “当前类所在包的路径 ”+ “/com/baijw/bean/config” + "School.xml"第二种写法,表示 “configPath + "School.xml"” 相对当前类加载器。可以将类加载器的位置理解为当前类的 classpath 所以去掉和不去掉 / 都将被解释为:“com/baijw/bean/config” + "School.xml"
com/baijw/bean/configSchool.xml
还是
com/baijw/bean/config/School.xml
如果是 com/baijw/bean/config/School.xml 那么 LZ 写的两种方式都返回 null
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/')
+"/"+name;
}
} else {
name = name.substring(1);
}
return name;
}