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