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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With