2013-07-30 171 views
0

我正在創建一些REST API。爲此我有一些應用程序級別的通用名稱值對。爲了配置這些名稱值對,我只是在WebContent中創建了一個xml文件,並從類的靜態塊中的xml中訪問了值,並使用靜態變量進行了初始化。因此,在xml中爲每個名稱給出的所有值將分配給來自類的靜態塊的相應靜態變量。無法訪問xml文件

我能夠訪問這些變量並獲得值比從REST API客戶端等各個類別。問題出現了,當我創建一個REST API客戶端來使用在同一個項目中創建的API時,FileNotFoundException會拋出我爲我的xml文件(WebContent/myxml.xml)提供的路徑。

我可以看到,它在尋找我日食路徑(/home/aneesh/eclipse/WebContent/myxml.xml)相同的XML文件。和FileNotFoundException拋出。 我該如何解決這個問題?

1. class which accessing xml file 
class Constants { 
    public static String name; 
    static { 
     initializeConstants(); 
    } 
public static void initializeConstants() { 
    try { 
    //initializing Constants 
    //"Reading file" 
    File xmlFile = new File("WebContent/myxml.xml"); 
    ....... 
    //file is getting read perfectly and "name" is initialized 
     } 
} 
2. class accepting static variable Constants.name 
    // accepting value of 'name' using Constants.name successfully 
    // writing a method which is accepting some parameters and using Constants.name. 
    // writing a "main" method and calling this class's methods will work perfectly. 
    // value of Constants.name will be accessible here. 

3. REST API created which will call methods of second class with parameters. 

4. Webscript client created for consuming above created API. 
    // Here the exception is coming. 
    // Eception is throwing from the class Constants 
    //Exception from Constants : FileNotFoundException 
java.io.FileNotFoundException: /home/aneesh/eclipse/eclipse/WebContent/myxml.xml (No such file or directory) 

那麼,爲什麼在這種情況下它尋找日食的路徑中的文件?如何解決它? 也試過把src文件夾放進去,但是不工作。

+0

請添加一些代碼。發生FileNotFoundException很可能是因爲確實沒有文件。再次檢查你的絕對路徑和相對路徑。 – snrlx

回答

0

嘗試給出路徑的WebContent // myxml.xml (注意雙斜線//)

+0

正斜槓如何改變結果? – snrlx

+0

我已經更新了這個問題。請閱讀 您給出的答案無效。 – Aneesh

0

你必須動態地找到XML文件的路徑。

您可以使用ServletContext對象的getRealPath() - 你可以用它喜歡:getRealPath(「/」),它返回您部署的應用程序的路徑。然後從那裏您可以導航到您的應用程序內所需的XML文件。

ServletContext的上下文= session.getServletContext();

字符串路徑= context.getRealPath( 「/」);

使用變量路徑並導航到您的XML。

+0

是的,這個想法得到了一個小小的改變。 – Aneesh

+0

見我的回答上述 – Aneesh

0

正如我我的課是不是一個Servlet類;我跟着;

public String getAppPath() { 
     java.net.URL r = this.getClass().getClassLoader().getResource("myxml.xml"); 
     String filePath = r.getFile(); 
     String result = new File(new File(new File(filePath).getParent()).getParent()).getParent(); 

     if (!filePath.contains("WEB-INF")) { 
      // Assume we need to add the "WebContent" folder if using Jetty. 
      result = FilenameUtils.concat(result, "WebContent"); 
     } 

     return result; 
    } 
+0

,但在行其投擲顯示java.lang.NullPointerException「字符串文件路徑= r.getFile();」有些時候。任何人都可以爲我解決這個問題嗎?在src文件夾中的資源文件(myxml.xml)的 – Aneesh

+0

飼養副本解決了這個問題。 – Aneesh