If in a JSP page I create a new file only giving it's name, it's created in the /bin directory of TOMCAT folder, rather in the same folder of the .jsp.
I'm not sure why this happens, seems to be not intuitive.
If in a JSP page I create a new file only giving it's name, it's created in the /bin directory of TOMCAT folder, rather in the same folder of the .jsp.
I'm not sure why this happens, seems to be not intuitive.
It's definitely intuitive, as the current directory of the running process is the bin folder.
You can try something like:
ServletContext context = session.getServletContext();
String realContextPath = context.getRealPath(request.getContextPath());
The java.io.File
knows nothing about the web application context where the JSP/Servlet code is running in. Any non-absolute (relative) path you pass in will be relative to current working directory, which is not per se the same in all environments. It depends on the way how you started the server/application. In an IDE like Eclipse, it's the project root folder. In command console, it's the currently opened directory. In Tomcat started as a service, it's the bin
folder of Tomcat.
You should always use absolute paths in java.io.File
and consorts, i.e. use the full disk file system path. In a JSP/Servlet webapplication you can use ServletContext#getRealPath()
to convert a relative web path to an absolute disk file system path which you can use further in Java IO stuff.
The relative web path has its root in the public webcontent, there where your JSP files and so on also are. Assuming that /file.ext
is located in the root of the public webcontent, then you can get an absolute disk file system path for /file.ext
inside a servlet the following way:
String relativeWebPath = "/file.ext";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// ...
That said, the JSP is the wrong place for this job, you should be doing this in a Servlet class.