A、実質的に.propertiesファイルのクラス定義は:
Propertiesクラスは、不変のプロパティセットを表します。プロパティは、ストリーム内のストリームから保存またはロードすることができます。各キーおよびプロパティリストのそれに対応する値は文字列です。
プロパティリストには、その「デフォルト値」として、他のプロパティのリストを含むことができ、そうでない場合は、検索キー属性のリストには、元の属性、第2の属性検索リストに。
プロパティのHashtableから継承、プットとのputAllメソッドPropertiesオブジェクトに適用することができますので。しかし、これらの方法は、彼らは、発信者がそのキーまたは値の文字列でないエントリを挿入することができますので、お勧めできません。代わりに、setPropertyメソッドを使用します。ストアまたはsaveメソッドを呼び出すための「妥協」プロパティオブジェクト内の(つまり、String以外のキーまたは値が含まれている)場合、呼び出しは失敗します。同様に、(String以外のキーが含まれている)「安全でない」Propertiesオブジェクトリストのメソッド、またはコールpropertyNames場合、コールは失敗します。
2つの一般的な方法:.
①getProperty(文字列キー)
指定されたキーを持つプロパティリスト内の属性を検索します。
②load(入力ストリームinStreamには)
入力ストリームからプロパティリスト(キーと要素のペア)を読み出します。
③propertyNamesは()
キーは個別のキーを含む、主要なプロパティリスト、デフォルトのプロパティリストで発見されていない場合、プロパティリストは、同じ名前のすべてのキーを列挙返します。
④setProperty(文字列のキーは、文字列値)は、
Hashtableのputメソッドを呼び出します。
3つのプロパティは、いくつかの方法で設定ファイルを読み込むの.java
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
loadProperties1();
readProperty2();
readProperty3();
}
//方式一:基于InputStream读取配置文件:
private static void loadProperties1() throws IOException {
Properties properties = new Properties();
// FileInputStream stream = new FileInputStream("db.properties");
InputStream stream = PropertiesDemo.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(stream);
System.out.println(properties.getProperty("username"));
System.out.println(properties.getProperty("password"));
}
//方法二通过Spring中的PropertiesLoaderUtils工具类进行获取:
private static void readProperty2() {
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("db.properties");
System.out.println(new String(properties.getProperty("username").getBytes("iso-8859-1"), "gbk"));
} catch (IOException e) {
e.printStackTrace();
}
}
//方法三通过 java.util.ResourceBundle 类读取:
private static void readProperty3() {
ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
//遍历取值
Enumeration enumeration = resourceBundle.getKeys();
while (enumeration.hasMoreElements()) {
try {
String value = resourceBundle.getString((String) enumeration.nextElement());
System.out.println(new String(value.getBytes("iso-8859-1"), "gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}