Java - Relative path of a file in a java web application

前端 未结 6 2007
星月不相逢
星月不相逢 2020-11-29 23:55

I want to read a file from a java web application. I don\'t want to give the absolute path of the file. I just want to put the file in some directory of my web application.<

6条回答
  •  [愿得一人]
    2020-11-30 00:35

    If you have a path for that file in the web server, you can get the real path in the server's file system using ServletContext.getRealPath(). Note that it is not guaranteed to work in every container (as a container is not required to unpack the WAR file and store the content in the file system - most do though). And I guess it won't work with files in /WEB-INF, as they don't have a virtual path.

    The alternative would be to use ServletContext.getResource() which returns a URI. This URI may be a 'file:' URL, but there's no guarantee for that.

提交回复
热议问题