2

假设我有一个目录,其中包含存储在“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 后台作业运行并使用模板。Object.class.getResource()如果我在 Tomcat servlet 中尝试该方法,它会返回 null。

无论运行时环境、应用程序引擎等如何,如何以安全的方式访问资源文件?

4

2 回答 2

1

我会使用您项目中的任何类(例如域类),使用 getClassLoader() 或 getContextClassloader() 并提供资源的路径。应该管用。

于 2012-11-20T20:14:32.607 回答
1

要从类路径读取文件,您可以使用:

getClass().getClassLoader().getResourceAsStream("path/to/resource");

还有一个简单有用的Spring实用程序ClassPathResource类:

Resource resource = new ClassPathResource("path/to/resource");
于 2012-11-20T20:22:28.880 回答