Servlets 获取WebContent中的资源相对路径

Servlets 获取WebContent中的资源相对路径,servlets,relative-path,webcontent,Servlets,Relative Path,Webcontent,我在Eclipse中构建了一个动态web项目MusicStore,我想访问位于WebContent/\u res/Songs.xml中的xml文件。我在常规Java类[不是servlet]中访问它时使用的方法是: URL url = this.getClass().getClassLoader().getResource("/"); String filePath = url.getFile(); String webAppLoc=new File(filePath).getParentFile

我在Eclipse中构建了一个动态web项目
MusicStore
,我想访问位于
WebContent/\u res/Songs.xml
中的xml文件。我在常规Java类
[不是servlet]
中访问它时使用的方法是:

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

在我看来,这是非常麻烦的。有没有更好、更有效的方法?谢谢

在这里,您可以尝试访问该文件

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());

 }
}

抱歉,此方法无效。我在一个动态webapp环境中,我需要的地址类似于:
/Users/username/CodeProjects/Eclipse/MAC\u EE/.metadata/.plugins/org.Eclipse.wst.server.core/tmp0/wtpwebapps/MusicStore
您的方法返回
/Applications/Eclipse-collection/Eclipse-EE/Eclipse.app/Contents/MacOS