この前の「JavaでCSV形式のファイルを読み書きするライブラリソースと使用例(BufferedReaderとFileReaderを利用する)」には、JavaでCSVファイルの読み書きすることを紹介しました。今回は、Javaでiniファイルを読み書きクラスソースです。JavaでXMLファイルの操作、DOM (Document Object Model) とSAX (Simple API for XML)のようなライブラリがありますので、一般的なJavaで開発されているシステムの設定ファイルなどは、XMLがよく使われていますが、iniファイルをいじって開発するプログラム/システムもあるし、DOM、SAXのような別のライブラリをインポートしたくない場合もありますね。
javaのjava.util.Propertiesなら、下記のようなソースで簡単なiniファイルを読めますが、「セッション」の概念がないことは、残念ですよね。
※XMLとは、文書やデータの意味や構造を記述するためのマークアップ言語の一つ。マークアップ言語とは、「タグ」と呼ばれる特定の文字列で地の文に構造を埋め込んでいく言語のことで、XMLはユーザが独自のタグを指定できることから、マークアップ言語を作成するためのメタ言語とも言われる。
以下はサンプルiniファイルの中身(sample.ini):
- [セッション1]
- key1=111111
- key2=222222
下記は読みだけJavaソース:
- try {
- java.util.Properties prop = new java.util.Properties();
- prop.load(new java.io.FileInputStream(”sample.ini”));
- String key1 = prop.getProperty(”key1″);
- String key2 = prop.getProperty(”key2″);
- System.out.println(”key1=” + key1);
- System.out.println(”key2=” + key2);
- } catch (java.io.IOException e) {
- e.printStackTrace();
- }
簡単なんですが、[セッション2]があれば面倒ですね。 下記のクラスでiniの読み込み操作は出来ます。
- package mytools;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * iniファイルを操作するクラス
- * @author DigitechLog.com
- * @version 2008-08-18
- */
- public final class ConfigurationFile {
- /**
- * iniファイルからエントリ設定値を取得する
- * @param file iniファイルのパス
- * @param section セクション名称
- * @param variable エントリ名称
- * @param defaultValue エントリ名称が存在していない場合デフォルト値
- * @return エントリの設定値
- * @throws IOException IO例外情報
- */
- public static String getProfileString(
- String file,
- String section,
- String variable,
- String defaultValue)
- throws IOException {
- String strLine, value = “” ;
- BufferedReader bufferedReader = new BufferedReader( new FileReader(file));
- boolean isInSection = false ;
- try {
- while ((strLine = bufferedReader.readLine()) != null ) {
- strLine = strLine.trim();
- strLine = strLine.split( ” [;] ” )[ 0 ];
- Pattern p;
- Matcher m;
- p = Pattern.compile( ” file://[//s*.*//s*//] ” );
- m = p.matcher((strLine));
- if (m.matches()) {
- p = Pattern.compile( ” file://[//s* " + section + " file://s*//] ” );
- m = p.matcher(strLine);
- if (m.matches()) {
- isInSection = true ;
- } else {
- isInSection = false ;
- }
- }
- if (isInSection == true ) {
- strLine = strLine.trim();
- String[] strArray = strLine.split( ” = ” );
- if (strArray.length == 1 ) {
- value = strArray[ 0 ].trim();
- if (value.equalsIgnoreCase(variable)) {
- value = “” ;
- return value;
- }
- } else if (strArray.length == 2 ) {
- value = strArray[ 0 ].trim();
- if (value.equalsIgnoreCase(variable)) {
- value = strArray[ 1 ].trim();
- return value;
- }
- } else if (strArray.length > 2 ) {
- value = strArray[ 0 ].trim();
- if (value.equalsIgnoreCase(variable)) {
- value = strLine.substring(strLine.indexOf( ” = ” ) + 1 ).trim();
- return value;
- }
- }
- }
- }
- } finally {
- bufferedReader.close();
- }
- return defaultValue;
- }
- /**
- * iniファイルエントリ設定値を変更する
- * @param file iniファイルのパス
- * @param section セクション名称
- * @param variable エントリ名称
- * @throws IOException IO例外情報
- */
- public static boolean setProfileString(
- String file,
- String section,
- String variable,
- String value)
- throws IOException {
- String fileContent, allLine,strLine, newLine, remarkStr;
- String getValue;
- BufferedReader bufferedReader = new BufferedReader( new FileReader(file));
- boolean isInSection = false ;
- fileContent = “” ;
- try {
- while ((allLine = bufferedReader.readLine()) != null ) {
- allLine = allLine.trim();
- if (allLine.split( ” [;] ” ).length > 1 )
- remarkStr = ” ; “ + allLine.split( ” ; ” )[ 1 ];
- else
- remarkStr = “” ;
- strLine = allLine.split( ” ; ” )[ 0 ];
- Pattern p;
- Matcher m;
- p = Pattern.compile( ” file://[//s*.*//s*//] ” );
- m = p.matcher((strLine));
- if (m.matches()) {
- p = Pattern.compile( ” file://[//s* " + section + " file://s*//] ” );
- m = p.matcher(strLine);
- if (m.matches()) {
- isInSection = true ;
- } else {
- isInSection = false ;
- }
- }
- if (isInSection == true ) {
- strLine = strLine.trim();
- String[] strArray = strLine.split( ” = ” );
- getValue = strArray[ 0 ].trim();
- if (getValue.equalsIgnoreCase(variable)) {
- newLine = getValue + “ = “ + value + “ “ + remarkStr;
- fileContent += newLine + ” \r\n ” ;
- while ((allLine = bufferedReader.readLine()) != null ) {
- fileContent += allLine + ” \r\n ” ;
- }
- bufferedReader.close();
- BufferedWriter bufferedWriter =
- new BufferedWriter( new FileWriter(file, false ));
- bufferedWriter.write(fileContent);
- bufferedWriter.flush();
- bufferedWriter.close();
- return true ;
- }
- }
- fileContent += allLine + ” \r\n ” ;
- }
- } catch (IOException ex) {
- throw ex;
- } finally {
- bufferedReader.close();
- }
- return false ;
- }
- /**
- * テストコード
- */
- public static void main(String[] args) {
- // String value = Config.getProfileString(”sysconfig.ini”, “Option”, “OracleDB”, “default”);
- // System.out.println(value);
- try {
- System.out.println(ConfigurationFile.setProfileString( ” d:/1.ini ” , ” Settings ” , ” SampSize ” , ” 111 ” ));
- } catch (IOException e) {
- System.out.println(e.toString());
- }
- }
- }
Enjoy!
Posted on Thursday, 8th January 2009 by admin
Tags: DOM, INI, Java, SAX, XML, クラスソース
Posted in Java | Comments (1) | 2,751 views

January 15th, 2009 at 12:31 pm
[...] ※1、XML概念の説明は「Javaでiniファイルを読み書きクラスソース」に参照できます。 [...]