Web系開発メモ

Java, C#, HTML, CSS, JavaScript のことなどを書いてます。

Java UTF-8のプロパティファイルを読み込む方法

JavaUTF-8 のプロパティファイルを読み込んで、値を取得する方法を書いていきます。

バージョン

1. プロパティファイルの準備

エンコーディングUTF-8 のファイルを作成します。

src/main/resources/msg.properties

hello=こんにちは

2. ResourceBundleを使う方法

ResourceBundle で値を取得する方法は以下の通りです。

src/main/java/org/example/ResourceBundleMain.java

package org.example;

import java.util.ResourceBundle;

public class ResourceBundleMain {
  public static void main(String[] args) {
    ResourceBundle bundle = ResourceBundle.getBundle("msg");
    System.out.println(bundle.getString("hello"));
  }
}

3. Propertiesを使う方法

Properties で値を取得する方法は以下の通りです。

src/main/java/org/example/PropertiesMain.java

package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesMain {
  public static void main(String[] args) throws IOException {
    try (
      InputStream is = PropertiesMain.class.getResourceAsStream("/msg.properties");
      InputStreamReader isr = new InputStreamReader(is, "UTF-8");
      BufferedReader reader = new BufferedReader(isr)
    ) {
      Properties properties = new Properties();
      properties.load(reader);
      System.out.println(properties.getProperty("hello"));
    }
  }
}

4. Propertiesで文字化けする場合

Properties#load(InputStream inStream) を使うと、日本語の値が文字化けしました。

package org.example;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MojibakePropertiesMain {
  public static void main(String[] args) throws IOException {
    try (
      InputStream is = MojibakePropertiesMain.class.getResourceAsStream("/msg.properties");
      BufferedInputStream stream = new BufferedInputStream(is)
    ) {
      Properties properties = new Properties();
      properties.load(stream);
      System.out.println(properties.getProperty("hello"));
    }
  }
}