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?
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?
Actually, you already know the relative path. You only yet have to understand the context and that you need to know the absolute local disk file system path.
If it is located in the webcontent, then you need to 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.
Alternatively, if it is located in the classpath, then you can use ServletContext#getResource()
to obtain an absolute URL
representing its location.
String classpathPath= "/STUFF/read.txt";
URL absoluteUrl = getServletContext().getResource(classpathPath);
File file = new File(absoluteUrl.toURI());
// Do your thing with File.
..or use ServletContext#getResourceAsStream()
to get it directly as InputStream
:
String classpathPath= "/STUFF/read.txt";
InputStream input = getServletContext().getResourceAsStream(classpathPath);
// Do your thing with InputStream.