如何以编程方式获取资源目录路径 [英] How to get resources directory path programmatically
问题描述
我有以下目录布局:
- src
- main
- java
- 资源
- sql(数据库脚本)
- spring(配置)
在ServletContextListener类中,我想访问SQL目录下的文件并列出它们。基本上我的问题是路径,因为我知道简单地列出目录下的文件是:
Within a ServletContextListener class, I want to access the files under the SQL directory and list them. Basically my problem is with the path, because I know that listing files under a directory in a nutshell is:
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
也许我可以使用 ServletContextEvent
对象来尝试构建 resources / sql的路径
Maybe I could use the ServletContextEvent
Object to try and build a path to resources/sql
public void contextInitialized(ServletContextEvent event) {
event.getServletContext(); //(getRealPath etc.)
}
是否存在设置该路径的内容相对的,非硬编码的方式?
像新文件(classpath:sql)
(最好是弹簧,如果可能的话)或者我应该怎么做servletContext指向 resources / sql
?
Does something exist to set that path in a relative, non-hardcoded way?
Something like new File("classpath:sql")
(preferably spring if possible) or what should I do with the servletContext to point at resources/sql
?
推荐答案
我假设的内容src / main / resources /
在构建时复制到.war内的 WEB-INF / classes /
。如果是这种情况你可以这样做(用实数值代替类名和被加载的路径)。
I'm assuming the contents of src/main/resources/
is copied to WEB-INF/classes/
inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).
URL sqlScriptUrl = MyServletContextListener.class
.getClassLoader().getResource("sql/script.sql");
这篇关于如何以编程方式获取资源目录路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!