如何以编程方式获取资源目录路径

我有以下目录布局:

  • Src
    • 总台
      • 爪哇咖啡
      • 资源
        • Sql (数据库脚本)
        • 弹簧(结构)
      • 网络应用

在 ServletContextListener 类中,我想访问 SQL 目录下的文件并列出它们。基本上,我的问题在于路径,因为我知道简而言之,在一个目录下列出文件是:

File folder = new File(path);
File[] listOfFiles = folder.listFiles();

也许我可以使用 ServletContextEvent对象来尝试构建到 resources/sql的路径

public void contextInitialized(ServletContextEvent event) {
event.getServletContext(); //(getRealPath etc.)
}

是否存在以相对的、非硬编码的方式设置路径的方法? 类似于 new File("classpath:sql")(如果可能的话,最好是 Spring)或者我应该如何处理 servletContext 来指向 resources/sql

264065 次浏览
import org.springframework.core.io.ClassPathResource;


...


File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

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");

Finally, this is what I did:

private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}

...

File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc