JavaでShiftJISのINIファイルを読み込む方法(Apache Commons Configurations)

自分用のメモになりますが、Shift_JIS で書かれた Windows 向け設定ファイル「INIファイル」を Java で読み込む方法を書いておきます。

Apache commons configuration を使った方法です。

maven の dependency はこちら。(バージョンは適宜書き換えてください)

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>Code language: HTML, XML (xml)

手元で試したときは commons-beanutils も必要でした。

で、Javaのソースはこんな感じ。

// INIファイル(Windows向け設定ファイル)読み込み
String iniPath = "c:\path\to\inifile.ini";
Charset iniCharset = Charset.forName("SJIS");
File file = new File(iniPath);
FileInputStream input;
InputStreamReader stream;
INIConfiguration iniConfig = new INIConfiguration();
try {
    // エンコーディング指定付きストリームでINIファイル読み込み
    input = new FileInputStream(file);
    stream = new InputStreamReader(input,iniCharset);
    iniConfig.read( new BufferedReader(stream) );
} catch (FileNotFoundException e) {
    e.printStackTrace();
    System.out.println("open file failed :"+ iniPath);
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    System.out.println("charset is not supported.");
} catch (ConfigurationException | IOException e) {
    e.printStackTrace();
    System.out.println("read file failed");
}

// INIファイルから変数へ移送
// Key は "セクション名" + "." + "キー名" で指定
Path baseDir = Paths.get(iniConfig.getString("SAMPLE_SECTION_NAME.SAMPLE_KEY_NAME"));
String userName = iniConfig.getString("SAMPLE_SECTION_LOGIN.SAMPLE_USER_NAME");Code language: Java (java)

読み取り時は、セクション名+"."+キー名でキー指定する形です。

INIConfiguration クラスの JavaDoc はこちら。

Hatena Pocket Line

コメントを記入