BlackHearts
BlackHearts

Reputation: 35

How to access folder near to my application in webapp?

my application is under wtpwebapps folder

wtpwebapps->myapp

and my files are under the wtpwebapps->files folder

wtpwebapps->files->file1
wtpwebapps->files->file2
wtpwebapps->files->file3

i've tried

request.getSession().getServletContext().getRealPath();

and got this path

workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps

when i append

"\files\file1"

to the path and acces that files then it gives me error that

The requested resource is not available

How to resolve this issue?

Upvotes: 0

Views: 211

Answers (4)

Ravindra HV
Ravindra HV

Reputation: 2608

Here is the code from a listener ....

System.out.println("Inside contextInitialized()");

System.out.println( servletContextEvent.getServletContext().getRealPath("") );
System.out.println( servletContextEvent.getServletContext().getRealPath("/") );

String filePath  = servletContextEvent.getServletContext().getRealPath("/public/file.txt");
File file = new File(filePath);

System.out.println( filePath );
System.out.println( file.exists() );

and its output...

Inside contextInitialized()
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\public\file.txt
true

Note that i have edited the path in between.

Upvotes: 0

Debojit Saikia
Debojit Saikia

Reputation: 10622

You can get the absolute path to your myApp/WEB-INF/classes directory as below:

URL resource = getClass().getResource("/");
String path = resource.getPath();

Now you can manipulate the path string to go to your files:

path = path.replace("your_app_name/WEB-INF/classes/", "");
path = path + "files/file1";

Here path is now referring to file1 present in wtpwebapps->files.

Upvotes: 0

Daniel V
Daniel V

Reputation: 45

Try this:

File currentDir=new File(request.getSession().getServletContext().getRealPath())
// or try this instead too:
// File currentDir=new File(".");

File myFile=new File(currentDir,"files\\file1");

Upvotes: 1

PeterMmm
PeterMmm

Reputation: 24630

If you append literally \files\file1 this won´t work because backslash is the escape character. Try

/files/file1

Java will convert to the platform path seperator.

Upvotes: 0

Related Questions