Gnik
Gnik

Reputation: 7426

How to read a directory in webapp folder of Maven web application

I'm working in maven web application. I need to read a directory(For ex: Files) in my webapp folder as follows,

Java.io.File file = new Java.io.File("path");

But I don't know how to specify the path of the directory here.

Upvotes: 2

Views: 5105

Answers (3)

Sean Reilly
Sean Reilly

Reputation: 21836

War files are not always expanded when they are deployed to an app server, so it's possible that a relative path won't exist in a filesystem at all.

Best bets are to use getResource from the class loader, which will return things in the class path (the WEB-INF/lib directory, etc), or to use the getResource() method of ServletContext to find things in the web application itself.

Upvotes: 0

Juvanis
Juvanis

Reputation: 25950

You shouldn't give local path addresses. Path should be a relative address, e.g. /files/images under your web archive (.war) folder.

To use relative paths properly, I suggest you to add your target folder to the resources definiton of POM.xml, check out these pages http://www.mkyong.com/maven/how-to-change-maven-resources-folder-location/ http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

You can refer to resources folder easily with something like this:

this.class.getResource("Mydirectory/SubDirectory");

Upvotes: 2

ŁukaszBachman
ŁukaszBachman

Reputation: 33735

When in doubt how relatives paths work, it's always best to do something like that:

System.out.println(new File("/my/desired/directory").getAbsolutePath());

This will print out the path in which classpath will look for the files.

Assuming:

  • servlet container webapps dir is located in: /var/lib/tomcat6/webapps
  • your webapp is called my-webapp.war

You should see the following output: /var/lib/tomcat6/webapps/my-webapp/my/desired/directory

Another pointer: you have mentioned that you are looking for webapp directory. I hope you know that this directory will not end up in *.war - it's contents will.

Upvotes: 0

Related Questions