Java-properties-class

提供:Dev Guides
移動先:案内検索

Java-プロパティクラス

プロパティはHashtableのサブクラスです。 キーが文字列で、値も文字列である値のリストを維持するために使用されます。

Propertiesクラスは、他の多くのJavaクラスで使用されます。 たとえば、環境値を取得するときにSystem.getProperties()によって返されるオブジェクトのタイプです。

プロパティは、次のインスタンス変数を定義します。 この変数は、Propertiesオブジェクトに関連付けられたデフォルトのプロパティリストを保持します。

Properties defaults;

以下は、プロパティクラスによって提供されるコンストラクタのリストです。

Sr.No. Constructor & Description
1

Properties( )

このコンストラクターは、デフォルト値を持たないPropertiesオブジェクトを作成します。

2

Properties(Properties propDefault)

デフォルト値にpropDefaultを使用するオブジェクトを作成します。 どちらの場合も、プロパティリストは空です。

Hashtableによって定義されたメソッドとは別に、プロパティは次のメソッドを定義します-

Sr.No. Method & Description
1

String getProperty(String key)

キーに関連付けられた値を返します。 キーがリストにもデフォルトプロパティリストにもない場合、nullオブジェクトが返されます。

2

String getProperty(String key, String defaultProperty)

キーに関連付けられた値を返します。キーがリストにもデフォルトプロパティリストにもない場合、defaultPropertyが返されます。

3

void list(PrintStream streamOut)

streamOutにリンクされた出力ストリームにプロパティリストを送信します。

4

void list(PrintWriter streamOut)

streamOutにリンクされた出力ストリームにプロパティリストを送信します。

5

void load(InputStream streamIn) throws IOException

streamInにリンクされた入力ストリームからプロパティリストを入力します。

6

Enumeration propertyNames( )

キーの列挙を返します。 これには、デフォルトのプロパティリストにあるキーも含まれます。

7

Object setProperty(String key, String value)

値をキーに関連付けます。 キーに関連付けられた以前の値を返します。そのような関連付けが存在しない場合はnullを返します。

8

void store(OutputStream streamOut, String description)

descriptionで指定された文字列を書き込んだ後、プロパティリストはstreamOutにリンクされた出力ストリームに書き込まれます。

次のプログラムは、このデータ構造でサポートされているメソッドのいくつかを示しています-

import java.util.*;
public class PropDemo {

   public static void main(String args[]) {
      Properties capitals = new Properties();
      Set states;
      String str;

      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

     //Show all states and capitals in hashtable.
      states = capitals.keySet();  //get set-view of keys
      Iterator itr = states.iterator();

      while(itr.hasNext()) {
         str = (String) itr.next();
         System.out.println("The capital of " + str + " is " +
            capitals.getProperty(str) + ".");
      }
      System.out.println();

     //look for state not in list -- specify default
      str = capitals.getProperty("Florida", "Not Found");
      System.out.println("The capital of Florida is " + str + ".");
   }
}

これは、次の結果を生成します-

出力

The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.

The capital of Florida is Not Found.