この前の「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. [セッション1]
  2. key1=111111
  3. key2=222222

下記は読みだけJavaソース:

  1. try {
  2. java.util.Properties prop = new java.util.Properties();
  3. prop.load(new java.io.FileInputStream(sample.ini));
  4. String key1 = prop.getProperty(key1);
  5. String key2 = prop.getProperty(key2);
  6. System.out.println(key1=” + key1);
  7. System.out.println(key2=” + key2);
  8. } catch (java.io.IOException e) {
  9. e.printStackTrace();
  10. }

簡単なんですが、[セッション2]があれば面倒ですね。 下記のクラスでiniの読み込み操作は出来ます。

  1. package   mytools;
  2.  
  3. import  java.io.BufferedReader;
  4. import  java.io.BufferedWriter;
  5. import  java.io.FileReader;
  6. import  java.io.FileWriter;
  7. import  java.io.IOException;
  8. import  java.util.regex.Matcher;
  9. import  java.util.regex.Pattern;
  10.  
  11. /**
  12. * iniファイルを操作するクラス
  13. * @author DigitechLog.com
  14. * @version 2008-08-18
  15. */
  16. public   final   class  ConfigurationFile  {
  17. /**
  18. * iniファイルからエントリ設定値を取得する
  19. * @param file iniファイルのパス
  20. * @param section セクション名称
  21. * @param variable エントリ名称
  22. * @param defaultValue エントリ名称が存在していない場合デフォルト値
  23. * @return エントリの設定値
  24. * @throws IOException IO例外情報
  25. */
  26. public   static  String getProfileString(
  27. String file,
  28. String section,
  29. String variable,
  30. String defaultValue)
  31. throws  IOException  {
  32. String strLine, value  =   “” ;
  33. BufferedReader bufferedReader  =   new  BufferedReader( new  FileReader(file));
  34. boolean  isInSection  =   false ;
  35. try   {
  36. while  ((strLine  =  bufferedReader.readLine())  !=   null )  {
  37. strLine  =  strLine.trim();
  38. strLine  =  strLine.split([;])[ 0 ];
  39. Pattern p;
  40. Matcher m;
  41. p  =  Pattern.compile(file://[//s*.*//s*//] ” );
  42. m  =  p.matcher((strLine));
  43. if  (m.matches())  {
  44. p  =  Pattern.compile(file://[//s* "   +  section  +   " file://s*//] ” );
  45. m  =  p.matcher(strLine);
  46. if  (m.matches())  {
  47. isInSection  =   true ;
  48. }   else   {
  49. isInSection  =   false ;
  50. }
  51. }
  52. if  (isInSection  ==   true )  {
  53. strLine  =  strLine.trim();
  54. String[] strArray  =  strLine.split( ” = ” );
  55. if  (strArray.length  ==   1 )  {
  56. value  =  strArray[ 0 ].trim();
  57. if  (value.equalsIgnoreCase(variable))  {
  58. value  =   “” ;
  59. return  value;
  60. }
  61. }   else   if  (strArray.length  ==   2 )  {
  62. value  =  strArray[ 0 ].trim();
  63. if  (value.equalsIgnoreCase(variable))  {
  64. value  =  strArray[ 1 ].trim();
  65. return  value;
  66. }
  67. }   else   if  (strArray.length  >   2 )  {
  68. value  =  strArray[ 0 ].trim();
  69. if  (value.equalsIgnoreCase(variable))  {
  70. value  =  strLine.substring(strLine.indexOf( ” = ” )  +   1 ).trim();
  71. return  value;
  72. }
  73. }
  74. }
  75. }
  76. }   finally   {
  77. bufferedReader.close();
  78. }
  79. return  defaultValue;
  80. }
  81. /**
  82. * iniファイルエントリ設定値を変更する
  83. * @param file iniファイルのパス
  84. * @param section セクション名称
  85. * @param variable エントリ名称
  86. * @throws IOException IO例外情報
  87. */
  88. public   static   boolean  setProfileString(
  89. String file,
  90. String section,
  91. String variable,
  92. String value)
  93. throws  IOException  {
  94. String fileContent, allLine,strLine, newLine, remarkStr;
  95. String getValue;
  96. BufferedReader bufferedReader  =   new  BufferedReader( new  FileReader(file));
  97. boolean  isInSection  =   false ;
  98. fileContent  =   “” ;
  99. try   {
  100.  
  101. while  ((allLine  =  bufferedReader.readLine())  !=   null )  {
  102. allLine  =  allLine.trim();
  103. if  (allLine.split([;]).length  >   1 )
  104. remarkStr  =   ” ; “   +  allLine.split( ” ; ” )[ 1 ];
  105. else
  106. remarkStr  =   “” ;
  107. strLine  =  allLine.split( ” ; ” )[ 0 ];
  108. Pattern p;
  109. Matcher m;
  110. p  =  Pattern.compile(file://[//s*.*//s*//] ” );
  111. m  =  p.matcher((strLine));
  112. if  (m.matches())  {
  113. p  =  Pattern.compile(file://[//s* "   +  section  +   " file://s*//] ” );
  114. m  =  p.matcher(strLine);
  115. if  (m.matches())  {
  116. isInSection  =   true ;
  117. }   else   {
  118. isInSection  =   false ;
  119. }
  120. }
  121. if  (isInSection  ==   true )  {
  122. strLine  =  strLine.trim();
  123. String[] strArray  =  strLine.split( ” = ” );
  124. getValue  =  strArray[ 0 ].trim();
  125. if  (getValue.equalsIgnoreCase(variable))  {
  126. newLine  =  getValue  +   “  =  “   +  value  +   “   “   +  remarkStr;
  127. fileContent  +=  newLine  +   ” \r\n ” ;
  128. while  ((allLine  =  bufferedReader.readLine())  !=   null )  {
  129. fileContent  +=  allLine  +   ” \r\n ” ;
  130. }
  131. bufferedReader.close();
  132. BufferedWriter bufferedWriter  =
  133. new  BufferedWriter( new  FileWriter(filefalse ));
  134. bufferedWriter.write(fileContent);
  135. bufferedWriter.flush();
  136. bufferedWriter.close();
  137.  
  138. return   true ;
  139. }
  140. }
  141. fileContent  +=  allLine  +   ” \r\n ” ;
  142. }
  143. } catch (IOException ex) {
  144. throw  ex;
  145. }   finally   {
  146. bufferedReader.close();
  147. }
  148. return   false ;
  149. }
  150.  
  151. /**
  152. * テストコード
  153. */
  154. public   static   void  main(String[] args)  {
  155. // String value = Config.getProfileString(”sysconfig.ini”, “Option”, “OracleDB”, “default”);
  156. // System.out.println(value);
  157. try   {
  158. System.out.println(ConfigurationFile.setProfileString(d:/1.ini ” ,  ” Settings ” ,  ” SampSize ” ,  ” 111));
  159. }   catch  (IOException e)  {
  160. System.out.println(e.toString());
  161. }
  162.  
  163. }
  164. }

Enjoy!

メインコンテンツEND ■
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Posted on Thursday, 8th January 2009 by admin

Tags: , , , , ,
Posted in Java | Comments (1) | 2,751 views

Related Posts

One Response to “Javaでiniファイルを読み書きクラスソース”

  1. jQueryを使ってXMLを解析操作する(サンプルソースコード含める) | DigiTechLog Dot Com Says:

    [...] ※1、XML概念の説明は「Javaでiniファイルを読み書きクラスソース」に参照できます。 [...]

Leave a Reply