views:

283

answers:

3

I am creating a FileOutputStream object. It takes a file or String as an argument in its constructor.

My question is, can I give it a relative URL as an argument for the location of a file, it doesn't seem to work, but I am trying to work out if this is possible at all (if not I will stop trying).

If it is not possible, how can I (from a servlet) get the absolute path (on the filesystem, not the logical URL) to the current location in such a way that I can pass that to the constructor.

Part of my problem is that my dev box is Windows but I will publish this to a Unix box, so the paths cannot be the same i.e. on Windows C:/.... and on unix /usr/...

+1  A: 

From the File javadoc:

A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

EDIT: Bozho is right, I didn't read that this was a servlet. I defer to his answer:

ServletContext.getRealPath(relativePath)

Tim Bender
This is not the way to go with servlets
Bozho
+2  A: 

ServletContext.getRealPath(relativePath)

Bozho
May be you mean getRealPath instead of getAbsolutePath
Andrea Polci
Yes, fixed it as you were commenting. Answering from mobile poses risks for such mistakes.
Bozho
Thanks I used ... request.getSession().getServletContext().getRealPath(request.getServletPath())
Ankur
@Ankur: you don't need to revive the session for this. If you extend `HttpServlet`, the `getServletContext()` method is already available to you! All you need to do is `getServletContext().getRealPath(relativeUrl);`.
BalusC
Yes you're right .. it works fine, thanks.
Ankur
+1  A: 

That should work with a relative path, yet be careful about what the current directory is. For instance if you are using Eclipse the current directory is the project directory (and not the directory containing the classes).

Jules Olléon
Thanks, that's useful .. I am using eclipse
Ankur