Java中的属性类
Properties 类表示一组持久的属性。属性可以保存到流中或从流中加载。它属于Java.util包。属性定义以下实例变量。此变量保存与Properties对象关联的默认属性列表。
Properties defaults: This variable holds a default property list associated with a Properties object.
属性类的特点:
- 属性是 Hashtable 的子类。
- 它用于维护一个值列表,其中键是字符串,值也是字符串,即;它可用于存储和检索属性文件中的字符串类型数据。
- 属性类可以指定其他属性列表,因为它是默认的。如果原始属性列表中不存在特定的关键属性,则将搜索默认属性。
- Properties 对象不需要外部同步,多个线程可以共享一个 Properties 对象。
- 此外,它还可用于检索系统的属性。
属性文件的优点
如果从属性记录中更改了任何数据,则不必重新编译Java类。它用于存储要习惯性更改的数据。
注意: Properties 类没有从其超类Hashtable继承负载因子的概念。
宣言
public class Properties extends Hashtable
属性的构造函数
1. Properties():这将创建一个没有默认值的Properties对象。
Properties p = new Properties();
2.Properties(Properties propDefault):第二个创建一个使用propDefault作为其默认值的对象。
Properties p = new Properties(Properties propDefault);
示例 1:下面的程序展示了如何使用 Properties 类从属性文件中获取信息。
让我们创建一个属性文件并将其命名为db.properties 。
数据库属性
username = coder
password = geeksforgeeks
代码
Java
// Java program to demonstrate Properties class to get
// information from the properties file
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// create a reader object on the properties file
FileReader reader = new FileReader("db.properties");
// create properties object
Properties p = new Properties();
// Add a wrapper around reader object
p.load(reader);
// access properties data
System.out.println(p.getProperty("username"));
System.out.println(p.getProperty("password"));
}
}
Java
// Java program to demonstrate Properties class to get all
// the system properties
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// get all the system properties
Properties p = System.getProperties();
// stores set of properties information
Set set = p.entrySet();
// iterate over the set
Iterator itr = set.iterator();
while (itr.hasNext()) {
// print each property
Map.Entry entry = (Map.Entry)itr.next();
System.out.println(entry.getKey() + " = "
+ entry.getValue());
}
}
}
Java
// Java program to demonstrate Properties class to create
// the properties file
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// create an instance of Properties
Properties p = new Properties();
// add properties to it
p.setProperty("name", "Ganesh Chowdhary Sadanala");
p.setProperty("email",
"ganeshs.gfg@gmail.com");
// store the properties to a file
p.store(new FileWriter("info.properties"),
"GeeksforGeeks Properties Example");
}
}
输出
示例 2:下面的程序显示了如何使用 Properties 类来获取所有系统属性。使用System.getProperties() 方法,我们可以获得系统的所有属性。
Java
// Java program to demonstrate Properties class to get all
// the system properties
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// get all the system properties
Properties p = System.getProperties();
// stores set of properties information
Set set = p.entrySet();
// iterate over the set
Iterator itr = set.iterator();
while (itr.hasNext()) {
// print each property
Map.Entry entry = (Map.Entry)itr.next();
System.out.println(entry.getKey() + " = "
+ entry.getValue());
}
}
}
输出
示例 3:下面的程序展示了如何使用 Properties 类来创建一个属性文件。
Java
// Java program to demonstrate Properties class to create
// the properties file
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
// create an instance of Properties
Properties p = new Properties();
// add properties to it
p.setProperty("name", "Ganesh Chowdhary Sadanala");
p.setProperty("email",
"ganeshs.gfg@gmail.com");
// store the properties to a file
p.store(new FileWriter("info.properties"),
"GeeksforGeeks Properties Example");
}
}
输出
属性方法
METHOD | DESCRIPTION |
---|---|
getProperty(String key) | Searches for the property with the specified key in this property list. |
getProperty(String key, String defaultValue) | Searches for the property with the specified key in this property list. |
list(PrintStream out) | Prints this property list out to the specified output stream. |
list(PrintWriter out) | Prints this property list out to the specified output stream. |
load(InputStream inStream) | Reads a property list (key and element pairs) from the input byte stream. |
load(Reader reader) | Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. |
loadFromXML(InputStream in) | Loads all of the properties represented by the XML document on the specified input stream into this properties table. |
propertyNames() | Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list. |
save(OutputStream out, String comments) | Deprecated. This method does not throw an IOException if an I/O error occurs while saving the property list. |
setProperty(String key, String value) | Calls the Hashtable method put. |
store(OutputStream out, String comments) | Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method. |
store(Writer writer, String comments) | Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method. |
storeToXML(OutputStream os, String comment) | Emits an XML document representing all of the properties contained in this table. |
storeToXML(OutputStream os, String comment, String encoding) | Emits an XML document representing all of the properties contained in this table, using the specified encoding. |
storeToXML(OutputStream os, String comment, Charset charset) | Emits an XML document representing all of the properties contained in this table, using the specified encoding. |
stringPropertyNames() | Returns an unmodifiable set of keys from this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list. |
在类Java.util.Hashtable 中声明的方法
METHOD | DESCRIPTION |
---|---|
clear() | Clears this hashtable so that it contains no keys. |
clone() | Creates a shallow copy of this hashtable. |
compute(K key, BiFunction super K,? super V,? extends V> remappingFunction) | Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
computeIfAbsent(K key, Function super K,? extends V> mappingFunction) | If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. |
computeIfPresent(K key, BiFunction super K,? super V,? extends V> remappingFunction) | If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. |
contains(Object value) | Tests if some key maps into the specified value in this hashtable. |
containsKey(Object key) | Tests if the specified object is a key in this hashtable. |
containsValue(Object value) | Returns true if this hashtable maps one or more keys to this value. |
elements() | Returns an enumeration of the values in this hashtable. |
entrySet() | Returns a Set view of the mappings contained in this map. |
equals(Object o) | Compares the specified Object with this Map for equality, as per the definition in the Map interface. |
get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
hashCode() | Returns the hash code value for this Map as per the definition in the Map interface. |
isEmpty() | Tests if this hashtable maps no keys to values. |
keys() | Returns an enumeration of the keys in this hashtable. |
keySet() | Returns a Set view of the keys contained in this map. |
merge(K key, V value, BiFunction super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
put(K key, V value) | Maps the specified key to the specified value in this hashtable. |
putAll(Map extends K,? extends V> t) | Copies all of the mappings from the specified map to this hashtable. |
rehash() | Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently. |
remove(Object key) | Removes the key (and its corresponding value) from this hashtable. |
size() | Returns the number of keys in this hashtable. |
toString() | Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ” , ” (comma and space). |
values() | Returns a Collection view of the values contained in this map. |
在接口Java.util.Map 中声明的方法
METHOD | DESCRIPTION |
---|---|
forEach(BiConsumer super K,? super V> action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
getOrDefault(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
putIfAbsent(K key, V value) | If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value. |
remove(Object key, Object value) | Removes the entry for the specified key only if it is currently mapped to the specified value. |
replace(K key, V value) | Replaces the entry for the specified key only if it is currently mapped to some value. |
replace(K key, V oldValue, V newValue) | Replaces the entry for the specified key only if currently mapped to the specified value. |
replaceAll(BiFunction super K,? super V,? extends V> function) | Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |