繁体   English   中英

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

[英]How to reference a file in the source dir from any Java code?

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM