【问题标题】:obtain resources relative path in WebContent获取WebContent中的资源相对路径
【发布时间】:2013-08-04 04:03:51
【问题描述】:

我在 Eclipse 中构建了一个动态 Web 项目 MusicStore,我想访问位于 WebContent/_res/Songs.xml 中的一个 xml 文件。我在普通Java类[not a servlet]中访问它的方法是:

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

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

【问题讨论】:

    标签: servlets relative-path webcontent


    【解决方案1】:

    这里你可以试试这个访问文件

    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_EE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/MusicStore你的方法返回/Applications/EclipseCollection/eclipse EE/Eclipse.app/Contents/MacOS
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2010-12-08
    • 2011-12-15
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多