开发者

In servlet (web app) how do I know the relative path? [duplicate]

开发者 https://www.devze.com 2022-12-23 06:09 出处:网络
This question already has answers here: How to find the working folder of a servlet based application in order to load resources
This question already has answers here: How to find the working folder of a servlet based application in order to load resources 开发者_StackOverflow社区 (3 answers) Closed 6 years ago.

I have a jsp file in the root of .war file. and then I have a folder named STUFF.

How do I get access to the file read.txt inside STUFF?

/Name_of_war/STUFF/read.txt is the correct path?


The webapp-relative path is /STUFF/read.txt.

You could use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path. This way you can use it further in the usual java.io stuff which actually knows nothing about the web context it is running in. E.g.

String relativeWebPath = "/STUFF/read.txt";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// Do your thing with File.

This however doesn't work if the server is configured to expand the WAR in memory instead of on disk. Using getRealPath() has always this caveat and is not recommended in real world applications. If all you ultimately need is just getting an InputStream of that file, for which you would likely have used FileInputStream, you'd better use ServletContext#getResourceAsStream() to get it directly as InputStream:

String relativeWebPath = "/STUFF/read.txt";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// Do your thing with InputStream.


If it is located in the classpath, or you can add the folder to the classpath, How about: ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream(fileName);

0

精彩评论

暂无评论...
验证码 换一张
取 消