Skip to main content

Accessing files using relative/absolute path

4 replies [Last post]
senore100
Offline
Joined: 2007-05-10

I am running my servlet using tomcat on my computer (instead of on the web). It involves accessing a password file. Here's how I put my files:

/myproj/Password/pwd.txt
/myproj/WEB-INF/web,xml
/myproj/WEB-INF/class/myservlet

To access the pwd.txt file, I try to get the absolute path to the file as follows:

String root = getServletConfig().getServletContext().getRealPath("/");
String adminFile = root + "Password/pwd.txt";

With tomcat, I am expecting to get

http://localhost:8080/myproj/Password/pwd.txt

as the location for the file.
Instead, I am getting the location of the file in the file system, that is:

D://Program Files/Apache Software Foundation/Tomcat 6.0/webapps/myproj/Password/pwd.txt

Yes, as it stands, my servlet can still find the file. But I'm not sure if this is a problem or not. I mean when it comes the time for me to deploy the servlet for real, can it still find the file?

Thanks!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tarbo
Offline
Joined: 2006-12-18

This is outside of my comfort area, but sure, as far as I can read from the API, this should work on different setups and/or servers just fine. :)

senore100
Offline
Joined: 2007-05-10

Thanks for replying.
I just feel a bit uneasy about using the absolute file system path instead of the webserver relative path, especially I've got to replace %20 with spaces.

tarbo
Offline
Joined: 2006-12-18

Check with the java.net.URL and java.net.URI classes. They can encode/decode URLs for you, and convert files to the proper format. Depending on what approach you wish to use, they should be helpful to you.

senore100
Offline
Joined: 2007-05-10

Thanks for your help!