Java Spring MVC应用程序的默认资源文件夹
我需要读取SpringMVC应用程序中控制器内的文件。 我可以将文件放置在什么默认位置,然后在控制器中执行以下操作:Java Spring MVC应用程序的默认资源文件夹,java,file,spring-mvc,Java,File,Spring Mvc,我需要读取SpringMVC应用程序中控制器内的文件。 我可以将文件放置在什么默认位置,然后在控制器中执行以下操作: @RequestMapping(value="/") public ModelAndView test(HttpServletResponse response) throws IOException{ File file = new File("simple_file_name_without_any_path_information.txt");
@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文件夹(请参阅) 您可能想试试Google Guava的Resources.getResource(“your_file.txt”),它会查看类路径,如果文件在Resources文件夹中,就会找到该文件。然后还可以使用Resources.readLines(url,Charsets.UTF_8)来读取它 它在幕后所做的(如果你不想使用图书馆)基本上是:
ClassLoader loader = Objects.firstNonNull(
Thread.currentThread().getContextClassLoader(),
Resources.class.getClassLoader());
URL url = loader.getResource(resourceName);
然后,您可以使用URL创建文件对象。谢谢,我使用了spring的ClasspathResource而不是guava的解决方案,但是将文件放在src/resources下的想法对我很有用。