简体   繁体   English

Spring MVC-无法在webapp / resources /中创建文件

[英]Spring MVC - Cannot create file at webapp/resources/

I want to create file at 'webapp/resources/' 我想在“ webapp / resources /”处创建文件

I used following code. 我用下面的代码。

String filepath = "classpath:webapp/resources/" + filename +".json";
File file = new File(filepath);

if (!file.exists()) {

            file.createNewFile();
}

but error occured. 但是发生了错误。

ex) no such file or directory 例如)没有这样的文件或目录

I think file path is incorrect. 我认为文件路径不正确。

I don't know real path of '/webapp/resources/'. 我不知道'/ webapp / resources /'的真实路径。

You have to get Physical Path from Servlet Context like 您必须从Servlet上下文获取物理路径 ,例如

   //add HttpServletRequest request in spring controller as parameter
   String phyPath = request.getSession().getServletContext().getRealPath("/");

   String filepath = phyPath + "resources/" + filename +".json";
   File file = new File(filepath);
   if (!file.exists()) {
            file.createNewFile();
   }

Be carefull before using it because after project re-deloyed,it will be flushed. 使用前请小心,因为重新部署项目后,它将被冲洗。 Other better option is to create CDN(Content Delivery Network) like server and store file there. 其他更好的选择是创建CDN(内容分发网络),例如服务器,并在其中存储文件。

java.io.File knows nothing about classpath: prefix. java.io.Fileclasspath:前缀一无所知。 It passes profided filepath directly to OS system function. 它将配置文件路径直接传递到OS系统功能。 And filepath is treated verbatim. 文件路径被逐字对待。 So you get error because there is no file with path classpath:webapp/resources/blah-blab.json . 因此,您会收到错误消息,因为没有路径为classpath:webapp/resources/blah-blab.json

One of your options is to use getRealPath . 您的选择之一是使用getRealPath But this is not portable and depends on how your application is deployed and what application server is used. 但这不是可移植的,并且取决于如何部署您的应用程序以及使用什么应用程序服务器。 In some cases application deployed as war is not unpacked, it is also possible that application is unpacked to temporary folder which is cleared between application server reboot. 在某些情况下,由于没有打开战争而部署的应用程序没有解压缩,也有可能将应用程序解压缩到临时文件夹中,该文件夹在应用程序服务器重新启动之间被清除。 In general this behavior is application server specific and should not be relied on. 通常,此行为是应用程序服务器特定的,因此不应依赖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM