Java Webアプリケーションで、CLASSPATH(つまり、 sourcesフォルダー内)に配置されているXMLファイルのInputStreamを取得したい場合、どうすればよいですか?
7 に答える
ClassLoader.getResourceAsStream()
。
以下のコメントで述べられているように、マルチClassLoader
環境(単体テスト、Webアプリなど)を使用している場合は、を使用する必要がある場合がありますThread.currentThread().getContextClassLoader()
。http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388を参照してください。
ClassLoader.class.getResourceAsStream("/path/file.ext");
これは、XMLファイルが正確にどこにあるかによって異なります。ソースフォルダ(「デフォルトパッケージ」または「ルート」内)にありますか、それともクラスと同じフォルダにありますか?
前者の場合、ファイルを見つけるために " /file.xml
"(先頭のスラッシュに注意)を使用する必要があり、ファイルを見つけるためにどのクラスを使用するかは関係ありません。
XMLファイルがクラスの隣にある場合はSomeClass.class.getResourceAsStream()
、ファイル名だけが最適です。
ClassLoader.class.getResourceAsStream("/path/to/your/xml")
コンパイルスクリプトがxmlファイルをCLASSPATHのどこかにコピーしていることを確認してください。
someClassWithinYourSourceDir.getClass()。getResourceAsStream();
この回答の「getResourceAsStream()」オプションのいくつかは私には機能しませんでしたが、これは機能しました:
SomeClassWithinYourSourceDir.class.getClassLoader()。getResourceAsStream( "yourResource");
提案された解決策を試しましたが、ファイル名のスラッシュが機能しませんでした。例:...()。getResourceAsStream( "/ my.properties"); nullが返されました
スラッシュの削除は機能しました:.... getResourceAsStream( "my.properties");
これはdocAPIからのものです。委任の前に、このアルゴリズムを使用して、指定されたリソース名から絶対リソース名が作成されます。
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').