首先获取应用程序(桌面和web应用程序)根目录的绝对路径;然后,获取相对于根目录的配置文件的香炉路径,通过这两个路径构建出资源的绝对路径。
类 | 方法 | 说明 |
Class | public URL getResource(String name) | name填写输入应用程序相对路径,如相对于根目录:/web/log4j.properties,得到结果:file:/E:/demo/jetbrain/cfg/c0001/target/classes/web/log4j.properties,然后通过getPath得到绝对地址路径;getResource在内部调用getClassLoader,然后找到相应的资源,可以直接使用getClassLoader,获取资源。 |
Class | public InputStream getResourceAsStream(String name) | 同上,获取的是资源的输入流。 |
ServletActionContext.getServletContext() | getRealPath | ServletActionContext.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties") |