5月 11th, 2008at 1:08
Tags: Java
J2SE1.5 Properties
ResourceBundleを使うとASCII文字に変換しなければならなくなるので、Propertyエディタを使うなりしないとめんどくさい。
しかし、Propertiesクラスを使えば、XML形式で値をやり取りでき、日本語もそのまま使えるらしいので、そっちを使ってファイルからの値取得を行う。
作りたいもの
- 「Key=Value」になっているファイルからKeyを元に値を取得
- Valueがカンマ区切りならList形式で値を返す
- Valueが「key=value,key=value・・・」ならばMap形式で値を返す
getStringValue(String key)や、getListValue(String key)などのメソッドを親で持ってしまって、それを継承した子クラスをファイルごとに作るシングルトンタイプのクラスを作成する。
親クラスAbstractProperties
コンストラクタでは、List値とMap値を保持するために初期化を行う。
でかいので添付しました。
protected AbstractProperties(String filePath) throws IOException{ this.listMap = new HashMap<String, List<String>>(); this.mapMap = new HashMap<String, Map<String, String>>(); this.properties = new Properties(); this.properties.loadFromXML(new FileInputStream(filePath)); }
listMapにはListで返した値を持っておき、はじめの一回だけ「文字列>List形式」への変換を行う。Mapでも同様。
public List<String> getListValue(String key){
List<String> value = this.listMap.get(key); if(value != null){ return value; }
//存在しない場合はListを生成する List<String> createList = splitString(properties.getProperty(key), ","); this.listMap.put(key, createList);
return createList; }
あとは下記のような型ごとの値を返すメソッドを用意する。
public double getDoubleValue(String key){ return Double.parseDouble(properties.getProperty(key)); }
public boolean getBooleanValue(String key){ return Boolean.parseBoolean(properties.getProperty(key)); }
public String getStringValue(String key){ return properties.getProperty(key); }
子供のクラスSampleProperties
子供のクラスではAbstractPropertiesを継承して、シングルトンの形で自分自身を返す実装をいれる。
package com.daipresents.util;
import java.io.IOException;
public class SampleProperties extends AbstractProperties {
private static SampleProperties properties;
private SampleProperties(String filePath) throws IOException{ super(filePath); }
public static void init(String filePath) throws IOException{ if(properties == null){ SampleProperties.properties = new SampleProperties(filePath); } }
public static AbstractProperties getInstance(){ return SampleProperties.properties; }}
読み込むXMLファイル
XMLファイルは以下の形式になる。
こんなことしなくてもListぽくXMLを書けばListにしてくれる仕組みがあればなー。
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties> <comment>Propertiesのテスト用サンプル</comment> <!-- int --> <entry key="001">-2147483648</entry> <!-- long --> <entry key="006">2147483648</entry> <!-- float --> <entry key="008">1.11</entry> <!-- double --> <entry key="012">1.11</entry> <!-- boolean --> <entry key="015">true</entry> <!-- String --> <entry key="023">真っ赤なお鼻の藤原さん</entry> <!-- List --> <entry key="025">one,two,three,four</entry> <!-- Map --> <entry key="031">one=1,two=2,three=3</entry> </properties>
課題
これだとファイルごとに子クラスができてしまう。




