obtain resources relative path in WebContent

1.1k views Asked by At

I have built a dynamic web project MusicStore in Eclipse, and I want to access an xml file located in WebContent/_res/Songs.xml. The method I used to access it in a regular Java class[not a servlet] is:

URL url = this.getClass().getClassLoader().getResource("/");
String filePath = url.getFile();
String webAppLoc=new File(filePath).getParentFile().getParent();
String resLoc=webAppLoc+"/_res/Songs.xml";

It seems to me that this is very cumbersome. Is there a better, more efficient way? thanks!

1

There are 1 answers

1
Sheel On

Here you can try this to access file

public class Test {
    public static void main(String[] args){
        //This gives me path for the  current working directory.
        String fileName = System.getProperty("user.dir");

        //This gives me path for the file that is residing in folder called "xml_tutorial".
        File file = new File(fileName + "../../xml_tutorial/sample.xlsx" );
        System.out.println(file.getCanonicalPath());

 }
}