Java 获取资源文件
获取资源文件一般使用getResource()方法,但Java中有两种类中提供该方法。详细情况可查看API,这里简单通过代码展示下区别:
//Class中的
Xx.class.getResource
//ClassLoader中的
Xx.class.getClassLoader().getResource
以下是演示代码
在eclipse环境中 abc.properties 在classpath下(src/main/resources/abc.properties)
System.out.println("getResource(\"abc.properties\")\t"+App.class.getResource("abc.properties"));
System.out.println("getResource(\"/abc.properties\")\t"+App.class.getResource("/abc.properties"));
System.out.println("getClassLoader().getResource(\"abc.properties\")\t"+App.class.getClassLoader().getResource("abc.properties"));
System.out.println("getClassLoader().getResource(\"/abc.properties\")\t"+App.class.getClassLoader().getResource("/abc.properties"));
//getClassLoader().getResource() 从classpath的根目录中查找
System.out.println("getClassLoader().getResource(\"\")\t"+App.class.getClassLoader().getResource(""));
//getResource() 从class所在的路径搜索
System.out.println("getResource(\"\")\t"+App.class.getResource(""));
System.out.println("getClassLoader().getResource(\"/\")\t"+App.class.getClassLoader().getResource("/"));
System.out.println("getResource(\"/\")\t"+App.class.getResource("/"));
以下是输出
getResource("abc.properties") null
getResource("/abc.properties") file:/F:/hbkx_work/workspace_hbkx/earlywarning/target/classes/abc.properties
getClassLoader().getResource("abc.properties") file:/F:/hbkx_work/workspace_hbkx/earlywarning/target/classes/abc.properties
getClassLoader().getResource("/abc.properties") null
getClassLoader().getResource("") file:/F:/hbkx_work/workspace_hbkx/earlywarning/target/classes/
getResource("") file:/F:/hbkx_work/workspace_hbkx/earlywarning/target/classes/com/kexion/earlywarning/
getClassLoader().getResource("/") null
getResource("/") file:/F:/hbkx_work/workspace_hbkx/earlywarning/target/classes/
但是当项目打成jar包后,一般一些可自定义的配置文件都放在单独的目录中(jar包外部),这时需要把这个目录指定成classpath以便读取。
直接运行class文件时可以通过在运行时指定classpath
@java -Xbootclasspath/a:../conf -jar ../lib/xxxxx.jar
上述脚本中-Xbootclasspath/a
指在启动时追加classpath路径。
详细情况http://blog.csdn.net/freud_zhihua/article/details/9446163
或百度搜索++-jar参数运行应用时classpath的设置方法。++
更详细的jar文件描述可参考http://www.ibm.com/developerworks/cn/java/j-jar/index.html