4
2

More than 3 years have passed since last update.

Java:ResourceBundleのpropertiesファイルを任意の場所に配置する

Last updated at Posted at 2020-07-02

はじめに

JavaでLocateを使用する際に ResourceBundle を使用することになった。

そこで ResourceBundle 用のpropertiesファイルをresourceディレクトリに配置した際に、対象のファイルが見つからないエラー(java.util.MissingResourceException)が発生したため、任意の場所にpuropertiesファイルを配置するための備忘録を以下に残す。

環境

▼ ディレクトリ構造

image.png

Main.java にて、日本とアメリカのLocaleを用意し、各ロケール用のpropertiesファイルをresourceディレクトリ直下に配置したが、propertiesファイルが見つからないと言われた。

原因は、クラスパスが以下で参照できないでいた為である。

  • C:\tool\pleiades\workspace\gold\bin

ちなみに、上記は次の記述で確認可能である。

Main.java

class Main {
    public static void main(String[] args) {
        System.out.println(System.getProperty("java.class.path"));
}

余談だが、上記のクラスパスの状態でpropertiesファイルを読み込ませるためには main ディレクトリ直下に配置する必要がある。

任意の場所にpropertiesファイルを配置して参照させるために

結論から言うと URLClassLoader を使用する。

Main.java
class Main {
    public static void main(String[] args) throws MalformedURLException {

        File dicDir = Paths.get(".\\resource").toFile(); // ★1

        URLClassLoader urlLoader; // ★2
        urlLoader = new URLClassLoader(new URL[]{dicDir.toURI().toURL()}); // ★3

        Locale localeJp = Locale.JAPAN;
        Locale localeUs = Locale.US;

        List<Locale> locales =
                new ArrayList<Locale>(Arrays.asList(localeJp, localeUs));

        for (Locale locale : locales) {
            ResourceBundle rb =
                    ResourceBundle.getBundle("Source" ,locale ,urlLoader); // ★4

            System.out.println(rb.getString("apple") + rb.getString("orange"));

        }
    }
}

任意の場所に配置したpropertiesファイルを参照する手順は以下の通り。

  1. ★1でpropertiesファイルを配置する場所を指定する。
  2. ★2と★3で1で指定したクラスローダのインスタンスを生成する。
  3. ★4で基底名がSourceのpropertiesファイルを参照する。

これで★1のパスを変更することで任意の場所にpropertiesファイルを参照することが出来るようになった。

おさらい

  • propertiesファイルのパスを指定しない場合:実行するjavaと同じ階層に配置
  • propertiesファイルのパスを指定する場合 :URLClassLoaderを使用する
4
2
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
4
2