2013-08-04 47 views
1

我在Eclipse中構建了一個動態web項目MusicStore,我想訪問位於WebContent/_res/Songs.xml的xml文件。我用來訪問它在一個普通的Java類[not a servlet]的方法是:在WebContent中獲取資源相對路徑

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

在我看來,這是非常麻煩的。有沒有更好,更有效的方法?謝謝!

回答

0

在這裏,你可以試試這個訪問文件

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

} 
} 
+0

對不起,這種方法是行不通的。我在一個動態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' – Will