Java中path的用法

一、以getClassLoader()获取资源,都是以classpath为根节点,不能在路径前加斜杠(/)

1、getClassLoader().getResourceAsStream

路径不对,返回null

InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("study/jdbc/db.properties");

 

2、getClassLoader().getResource

返回具体的路径:file:/E:/workspaces/Test/WebRoot/WEB-INF/classes/study/jdbc/db.properties;路径写错会返回null

URL url1 = JdbcUtils.class.getClassLoader().getResource("study/jdbc/db.properties");

 

 

二、java项目获取资源也是以classpath为根节点,但是必须加上斜杠(/),javaweb项目通过上下文路径获取资源也是以webapp为根节点(在tomcat6中前面必须加斜杠(/))

1、getResourceAsStream

路径不对,返回null

InputStream in = Test.class.getResourceAsStream("/study/jdbc/db.properties");

 

2、getResource

以classpath为根节点,必须在路径前加斜杠(/),返回具体的路径:file:/E:/workspaces/Test/WebRoot/WEB-INF/classes/study/jdbc/db.properties

路径写错会返回null

URL url = Test.class.getResource("/study/jdbc/db.properties");

 

 

3、getServletContext().getResource

返回具体的路径:file:/E:/workspaces/Test/WebRoot/WEB-INF/classes/study/jdbc/db.properties;否则返回null

URL url = getServletContext().getResource("/WEB-INF/study/jdbc/db.properties");

 

4、getServletContext().getResourceAsStream

路径不对,返回null

InputStream in = getServletContext().getResourceAsStream("/WEB-INF/study/jdbc/db.properties");

 

总结:以斜杠(/)开头,一般都是根目录,否则是当前目录

posted @ 2016-04-06 23:46  掉尾瓶  阅读(2482)  评论(0)    收藏  举报