2008年 4月 07日 月曜日
[Sun SPOT メモ] プロパティ(Properties)をリソースファイル(Resource Files)から読み込む。
JukeBox デモの実装を検討していて、アプリケーションで使うプロパティの値を外部リソースファイルから読み込みたくなり、ドキュメントでやり方を調べたので、忘れないよう以下にメモしておきます。
例えば、メロディを演奏するクラスを曲毎に用意することにして、これらを以下のキー/値の組:
| <ユニークな曲番>=<クラス名> |
各メロディ演奏クラスは以下のインタフェースを implements しています。
| package org.sunspotworld; public interface MelodyPlayer { void play(); } |
また、DefaultPlayer、PolkkaPlayer、FF6ButtlePlayer クラスはそれぞれ次のような感じで実装します。
package org.sunspotworld; |
package org.sunspotworld; |
package org.sunspotworld; |
アプリケーションから利用するリソースファイルは、resources ディレクトリ以下に格納します。 今回は、下図のように melodyplayers.properties をresources ディレクトリ直下に配置しました。
リソースファイルは、getResourceAsStream メソッドを使って 読み込むことができます。
| InputStream in = getClass().getResourceAsStream("/somefilename" ); |
それでは、melodyplayers.properties ファイルを読み込んでメロディを演奏する簡単なSun SPOTアプリケーションを作成して、実行してみましょう。
以下にソースコードを示します:
| package org.sunspotworld; import com.sun.spot.util.*; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class ResourceFileTestSpot extends MIDlet { protected void startApp() throws MIDletStateChangeException { new BootloaderListener().start(); // monitor the USB (if connected) and recognize commands from host Properties props = extractProps("/melodyplayers.properties" ); System.out.println("TestSpot: Begin" ); play(props); System.out.println("TestSpot: End" ); while (true) { Utils.sleep(2000L); } } // プロパティで指定された Playerの演奏を実行 private void play(Properties props) { Enumeration keys = props.propertyNames(); while (keys.hasMoreElements()) { try { String key = (String)keys.nextElement(); // キー: 1,2,3... String playerName = props.getProperty(key); // Playerのクラス名 // クラス名を指定して、Playerの新しいインスタンスを生成 MelodyPlayer player = (MelodyPlayer)Class.forName(playerName).newInstance(); // 演奏の実行 player.play(); } catch (Exception ex) { ex.printStackTrace(); } } } // Propertiesインスタンスへのプロパティの読み込み private Properties extractProps(String filename) { Properties props = new Properties(); InputStream in = null; try { // リソースファイルのオープン in = getClass().getResourceAsStream(filename); if (in != null) { // プロパティのロード props.load(in); } else { System.out.println("in == null" ); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) {} } } return props; } protected void pauseApp() { } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { } } |
アプリケーションをSun SPOTに配備して実行します。。。
。。。
リソースファイルの読込みに成功しました 
Posted at 04:00午後 4 07, 2008 by Shuichi Machida in SunSPOT | 投稿されたコメント[0]