⼀、以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;路径写错会返回nullURL 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;否则返回nullURL url = getServletContext().getResource(\"/WEB-INF/study/jdbc/db.properties\");
4、getServletContext().getResourceAsStream路径不对,返回null
InputStream in = getServletContext().getResourceAsStream(\"/WEB-INF/study/jdbc/db.properties\");
总结:以斜杠(/)开头,⼀般都是根⽬录,否则是当前⽬录
因篇幅问题不能全部显示,请点此查看更多更全内容