0

When I would like to get a real path in Java EE, using this instructions:

String rootPath = getServletConfig().getServletContext().getRealPath("/");
System.out.println(rootPath);

The result is: C:\Users\saad\Desktop\pds.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Metier\

And normaly, I have to get this result:

C:\Users\saad\Desktop\pds\Metier\

Can anyone help me, please?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Saad Lamarti
  • 300
  • 1
  • 5
  • 15

2 Answers2

2

This is an excellent example of why the concept of "filesystem path relative to the application" really has no meaning in a servlet. When a servlet is deployed into a container, there is no guarantee that it resides at a real filesystem location. The servlet container could choose to execute it directly from the .war file without expanding it, or it could be reading the application code from a URL that is not backed by a traditional file system at all.

In your case, the long path you got back is exactly where Eclipse deployed your application. That path was 100% correct in that context, because if you look at the filesystem at that location you'll find a copy of your application, but obviously not what you were expecting.

In general, it is not possible to portably refer to any file path relative to your application because the path may not exist.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

Path to Tomcat dir (tomcat/bin):

File inputFile = new File("file.xml"); // tomcat_dir/bin/file.xml

Path to other Tomcat directories, "webapps" for example:

File inputFile = new File("../webapps/file.xml"); // tomcat_dir/webapps/file.xml

Good way to get rid of the absolute paths :)

ddb
  • 2,423
  • 7
  • 28
  • 38
Fr333du
  • 191
  • 13