I am currently working on a web application. In some part of this application I want to upload files to a certain directory. Initially, when I wrote my test cases this worked perfectly:
final static String IMAGE_RESOURCE_PATH = "res/images";
...
File directory = new File(IMAGE_RESOURCE_PATH + "/" + productId);
if(!directory.exists()) {
directory.mkdirs();
}
This creates the directory wherein the file will be uploaded. The resulting path will be:
[project root folder]/res/images/[productId]
Since deploying the application to a server (Tomcat 7), the directory gets created in the root of the IDE I’m using, which is a bit confusing to me.
eg: C:\Eclipse86\res\images
Any idea how I can revert back to the project path with just plain Java without using some hacked technique or hard-coding the path?
If you don’t specify the absolute path, your directory will be created inside (or, if correctly, relative to) working directory of the application.
If you want to get directory inside your web application you should use
getServletContext().getRealPath(String path). For example,getServletContext().getRealPath("/")is the path to the root directory of the application.To create directory with path
[project root folder]/res/images/[productId], do something like this: