Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

servlets

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?

like image 854
EugeneP Avatar asked Mar 16 '10 15:03

EugeneP


1 Answers

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.
like image 199
BalusC Avatar answered Oct 28 '22 05:10

BalusC