如何从任何Java代码引用源目录中的文件?

时间:2012-11-20 20:04:25

标签: java

假设我有一个目录,其中包含存储在“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。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

要从 classpath 读取文件,您可以使用:

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

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

Resource resource = new ClassPathResource("path/to/resource");