3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

-cpオプションにプロパティファイルのパスを指定したにも関わらず、クラスパスとして認識されない

Posted at

環境

この記事は以下の環境で、稼働確認を実施しました。

C:\>java -version
openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)

事象

以下のMain.javaはクラスパス上に存在するqueen.propertiesを読み込んだのち、その内容を整形して表示するものです。

Main.java
import java.io.IOException;
import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        try (var in = Main.class.getClassLoader().getResourceAsStream("queen.properties")) {
            var properties = new Properties();
            properties.load(in);

            for (var key : properties.stringPropertyNames()) {
                var value = properties.getProperty(key);
                var message = String.format("key=`%s` value=`%s`", key, value);
                System.out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

なおqueen.propertiesの内容は次の通りです。

queen.properties
queen.vocal  = Freddie Mercury
queen.guitar = Brian May
queen.bass   = John Deacon
queen.drum   = Roger Taylor

さてMain.javajavacによりコンパイルして、Main.classを生成し、以下の通り実行したところ、エラーが発生し、想定通りの挙動を見せませんでした。

C:\>java -cp properties\queen.properties; Main
Exception in thread "main" java.lang.NullPointerException: inStream parameter is null
        at java.base/java.util.Objects.requireNonNull(Objects.java:246)
        at java.base/java.util.Properties.load(Properties.java:403)
        at Main.main(Main.java:8)

このケースではpropertiesディレクトリに格納されたqueen.propertiesをクラスパスに追加したいという意図がありました。そのため、クラスパスを指定する-cpオプションにproperties\queen.propertiesを指定したのですが、うまく動作しなかったようです。

原因と対策

ワイルドカード(*)を利用する場合などを別にすると、クラスパスへの指定方法はおおよそ次のようなルールになっているようです。

  • jarファイルやzipファイルはファイル名を指定する。
  • それ以外はディレクトリ名を指定する。

propertiesファイルをクラスパスに指定したいというのが今回の要望でした。したがって、クラスパスの指定方法としては後者が正解です。そこで、-cpオプションにファイル名ではなく、ディレクトリ名を指定したところ、想定通りの挙動になりました。

C:\>java -cp properties; Main
key=`queen.guitar` value=`Brian May`
key=`queen.drum` value=`Roger Taylor`
key=`queen.vocal` value=`Freddie Mercury`
key=`queen.bass` value=`John Deacon`

参考

「クラス・パスの設定」

3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?