In servlet (web app) how do I know the relative path? [duplicate]
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);
精彩评论