Skip to content

Instantly share code, notes, and snippets.

@mumumu
Created December 1, 2011 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumumu/1412702 to your computer and use it in GitHub Desktop.
Save mumumu/1412702 to your computer and use it in GitHub Desktop.
package com.example.ini;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import org.ini4j.Ini;
import org.ini4j.IniPreferences;
import org.ini4j.InvalidFileFormatException;
public class ExampleIniConfig {
/*
* Ini オブジェクト
*/
private static Ini all_ini_entries = null;
/*
* 設定オブジェクト
*/
private static Preferences ini_prefs = null;
/*
* 設定ファイルパス(クラスパスが通った場所からの相対パス)
*/
private static String CONFIG_FILE = "com/example/ini/example.ini";
/*
* 設定ファイルを読み込みます。
*
* @param filename ファイル名(クラスパスが通った場所からの相対パス)
*/
private static void load(String fileName) throws IOException, InvalidFileFormatException {
ClassLoader cloader = Thread.currentThread().getContextClassLoader();
if (cloader == null) {
cloader = ExampleIniConfig.class.getClassLoader();
}
all_ini_entries = new Ini(new File(fileName));
ini_prefs = new IniPreferences(all_ini_entries);
}
/**
* 特定のセクションの設定全てを Preferences オブジェクトとして返します
*
* @param sectionName - セクション名
* @return 設定オブジェクト
*/
public static Preferences getSection(String sectionName) {
if (ini_prefs == null) {
try {
load(CONFIG_FILE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return ini_prefs.node(sectionName);
}
/**
* セクション名全てを配列として返します
*
* @return セクション名の配列
*/
public static String[] getAllSections() {
if (ini_prefs == null) {
try {
load(CONFIG_FILE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Set<String> all_section_names = all_ini_entries.keySet();
return (String[])all_section_names.toArray(new String[0]);
}
/**
* 特定のセクションが存在するか否かを判定します
*
* @param sectionName - セクション名
* @return セクションが存在すれば true 存在しなければ false
*/
public static boolean sectionExists(String sectionName) {
if (ini_prefs == null) {
try {
load(CONFIG_FILE);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
try {
return ini_prefs.nodeExists(sectionName);
} catch (BackingStoreException e) {
e.printStackTrace();
return false;
}
}
/**
* 特定の設定をboolean値として取得します
*
* @param sectionName - セクション名
* @param key - 設定のキー
* @return 設定値。設定が存在しない場合はfalse
*/
public static boolean getBoolean(String sectionName, String key) {
Preferences section = getSection(sectionName);
return section.getBoolean(key, false);
}
/**
* 特定の設定をString値として取得します
*
* @param sectionName - セクション名
* @param key - 設定のキー
* @return 設定値。設定が存在しない場合は空文字列
*/
public static String get(String sectionName, String key) {
Preferences section = getSection(sectionName);
return section.get(key, "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment