2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Class#getResourceAsStream(String) の引数に指定する値は何?

Last updated at Posted at 2023-01-25

以下のいずれかです。

  • クラスパス直下にある場合は、 /hoge.txt のように「スラッシュ + ファイル名」を指定
  • クラスのパッケージ名と同じ場所にある場合は、hoge.txt のように「ファイル名」を指定

詳しくは Class#getResourceAsStream(String name) - JavaDoc を参照し…、分かりにくいので解説します。

「スラッシュ + ファイル名」で指定する場合

通常、resources からのパスを指定する場合に使います。
resources 直下に sample.txt を配置
上の図では resources/samaple.txt にファイルを配置しています。
これを jar ファイルにコンパイルした場合、クラスパス直下に sample.txt が配置されます。
resources 直下に sample.txt を配置した場合のコンパイル結果
そのため、 Main.class.getResourceAsStream("/sample.txt") とすれば、sample.txtInputStream を取得できます。

「ファイル名」で指定する場合

通常、resources/<パッケージ名> の位置にあるファイルを指定する場合に使います。
パッケージ階層と同じ場所に sample.txt を配置
上の図では resources/org/example/samaple.txt にファイルを配置しています。
これを jar ファイルにコンパイルした場合、org/example/sample.txt に配置されます。
パッケージ階層と同じ場所に sample.txt を配置した場合のコンパイル結果
そのため、Main.class.getResourceAsStream("sample.txt") とすれば、org/example/sample.txtInputStream を取得できます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?