0

いくつかの REST API を作成しています。このために、いくつかのアプリケーション レベルの共通名と値のペアがあります。これらの名前と値のペアを構成するために、WebContent で xml ファイルを作成し、クラスの静的ブロックで xml から値にアクセスし、静的変数で初期化しました。したがって、xml 内の各名前に指定されたすべての値は、クラスの静的ブロックからそれぞれの静的変数に割り当てられます。

これらの変数にアクセスし、REST API クライアント以外の各クラスで値を取得できます。問題は、同じプロジェクトで作成された API を使用するための REST API クライアントを作成しているときに、xml ファイル (WebContent/myxml.xml) に指定したパスに対して FileNotFoundException がスローされることです。

私のEclipseパス(/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)

では、なぜこの場合、Eclipse のパスでファイルを探すのでしょうか? それを解決する方法は?src フォルダーにも入れてみましたが、機能しませんでした。

4

3 に答える 3

0

パスを WebContent//myxml.xml として指定してみてください (二重スラッシュ // に注意してください)。

于 2013-07-30T12:01:51.303 に答える
0

私のクラスはサーブレットクラスではありません。私はついていきます;

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;
    }
于 2013-07-31T05:46:55.890 に答える