【问题标题】:Default resources folder for Spring MVC appSpring MVC 应用程序的默认资源文件夹
【发布时间】:2014-05-21 14:32:18
【问题描述】:

我需要在 Spring MVC 应用程序的控制器中读取文件。 我可以放置文件的默认位置是什么,然后在我的控制器中我可以执行以下操作:

@RequestMapping(value="/")
public ModelAndView test(HttpServletResponse response) throws IOException{  

        File file = new File("simple_file_name_without_any_path_information.txt");

            // reading in the file ....
}

为了让它工作,我需要做任何额外的配置吗? 我尝试将文件放在 webapp\resources 或 webapp\WEB-INF 或普通 webapp 下。

所有选项都不起作用。

【问题讨论】:

    标签: java file spring-mvc


    【解决方案1】:

    使用 java.io.File,默认路径将是启动路径,在您的情况下,它可能是应用程序服务器的 /bin 文件夹(请参阅In Java, what is the default location for newly created files?)。

    您可能想改用 Google Guava 的 Resources.getResource("your_file.txt"),它在类路径上查找,如果文件在资源文件夹中,它将找到该文件。然后你也可以使用 Resources.readLines(url, Charsets.UTF_8) 来读取它。

    它在幕后的作用(如果您不想使用库)基本上是:

    ClassLoader loader = Objects.firstNonNull(
        Thread.currentThread().getContextClassLoader(),
        Resources.class.getClassLoader());
    URL url = loader.getResource(resourceName);
    

    然后您可以使用 URL 创建一个 File 对象。

    【讨论】:

    • 谢谢,我使用了 spring 的 ClasspathResource 而不是 guava 的解决方案,但是将文件放在 src/resources 下的想法对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    相关资源
    最近更新 更多