gpt4 book ai didi

java - Spring MVC 应用程序的默认资源文件夹

转载 作者:行者123 更新时间:2023-12-01 12:57:08 25 4
gpt4 key购买 nike

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

@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.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 对象。

关于java - Spring MVC 应用程序的默认资源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com