35

私の Maven プロジェクトでは、src/main/resources に xls ファイルがあります。私がそれを読むと、次のようになります。

 InputStream in = new
 FileInputStream("src/main/resources/WBU_template.xls");

全て大丈夫。

ただし、getResourceAsStream で InputStream として読みたい。これを行うと、スラッシュの有無にかかわらず、常に NPE が発生します。

     private static final String TEMPLATEFILE = "/WBU_template.xls";
     InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);

スラッシュがあるかどうかに関係なく、または getClassLoader() メソッドを使用しても、NullPointer が返されます。

私もこれを試しました:

URL u = this.getClass().getResource(TEMPLATEFILE);
System.out.println(u.getPath());

コンソールに.../target/classes/WBU_template.xlsと表示され、NullPointerを取得します。

私は何を間違っていますか?

4

2 に答える 2

52

FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.

getResourceAsStream() will load a file path relative from your application's classpath.

When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.

When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

The file should be located in src/main/resources when loading using Class loader

In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.

于 2012-12-20T07:47:26.443 に答える
2

I usually load files from WEB-INF like this

session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")
于 2012-12-20T07:41:48.680 に答える