>假设我有一个目录,其中包含存储在"src"源目录中某处的资源文件,其中包含模板,配置文件等内容。
我知道从 Servlet 中,我可以按名称访问文件,例如:
File file = new File(ServletContact.getResource("some/namespace/filename.txt").getPath());
从非 Servlet 我可以做到:
File file = new File(Object.class.getResource("some/namespace/filename.txt").getPath());
但问题是我有代码需要访问这些资源文件,并且可以独立于运行时环境运行。 例如,一些代码使用servlet中的模板(在Tomcat 7下)。 其他代码作为 Quartz 后台作业运行并使用模板。 如果我在 Tomcat servlet 中尝试 Object.class.getResource()
方法,它会返回 null。
如何以安全的方式访问资源文件,而不管运行时环境、应用引擎等如何?
要从类路径中读取文件,您可以使用:
getClass().getClassLoader().getResourceAsStream("path/to/resource");
此外,还有简单实用的 Spring 实用程序ClassPathResource
类:
Resource resource = new ClassPathResource("path/to/resource");
我会使用项目中的任何类(例如域类),使用 getClassLoader() 或 getContextClassloader() 并提供资源的路径。应该工作。