Method | Parameter format | Lookup failure behavior | Usage example |
ClassLoader. | "/"-separated names; no leading "/" (all names are absolute) | Silent (returns null ) | this.getClass().getClassLoader() |
Class. | "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package | Silent (returns null ) | this.getClass() |
ResourceBundle. | "."-separated names; all names are absolute; .properties suffix is implied | Throws uncheckedjava.util.MissingResourceException | ResourceBundle.getBundle |
第一种方法:通过ClassLoader去加载资源。参数需要从classpath的入口来算起。也就是说需要取全路径名称。
第二种方法:通过Class来加载。这种参数,前面的package已经知道了,所以,前面这一部分就已经省去了,只需要写后面的部分就可以了。
第三种方法:通过ResourceBundle来加载。和ClassLoader一样,不过参数是用.来分割的,而不是用/来分割的:)
在实际中,根据资源文件打包位置的不同,选择不同的方法。
在我的程序中:由于sql文件和class是在同一个package下,可以选择第二种方法。当然,也可以选择第一种方法。我就是这么弄的。
如果sql和class不在同一个package下,那么,最好还是使用ClassLoader来加载,也就是第一种方法。
嘿嘿,不错。