How to provide relative path in File class to upload any file? [duplicate]

I want to provide a relative path

Never do that in a webapp. The working directory is not controllable from inside the code.


because the program should work in both linux and windows env.

Just use "/path/to/uploaded/files". It works equally in both environments. In Windows it will only be the same disk as where the server runs.

File file = new File("/path/to/uploaded/files", filename);
// ...

This is what i am using to upload

 realPath = getServletContext().getRealPath(/files);
 destinationDir = new File(realPath);

You should not store the files in the webcontent. This will fail when the WAR is not expanded and even when it is, all files will get lost whenever you redeploy the WAR. Store them outside the WAR in an absolute location, e.g. /path/to/uploaded/files as suggested before.

See also:

  • getResourceAsStream() vs FileInputStream
  • Best Location for Uploading file
  • Simplest way to serve static data from outside the application server in a Java web application