044_Properties工具类
1. Properties繼承HashTable
public class Propertiesextends Hashtable<Object,Object>
2. Properties類表示了一個(gè)持久的屬性集。Properties可保存在流中或從流中加載。屬性列表中每個(gè)鍵及其對(duì)應(yīng)值都是一個(gè)字符串。
3. 官方推薦使用setProperty方法, 不要使用put和putAll方法
4. load(Reader)/store(Writer, String)簡(jiǎn)單的面向行的格式在基于字符的流中加載和存儲(chǔ)屬性。除了輸入/輸出流使用ISO 8859-1字符編碼外,
load(InputStream)/store(OutputStream, String)方法與load(Reader)/store(Writer, String)對(duì)的工作方式完全相同。
5. loadFromXML(InputStream)和storeToXML(OutputStream, String, String)方法按簡(jiǎn)單的XML格式加載和存儲(chǔ)屬性。默認(rèn)使用UTF-8字符編碼。
6. Properties是線程安全的, 多個(gè)線程可以共享單個(gè)Properties對(duì)象而無(wú)需進(jìn)行外部同步。
7. 使用Properties工具類
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; import java.util.Set;public class UseProperties {/*** Properties的keys和loadFromXML方法加載數(shù)據(jù)* @throws FileNotFoundException* @throws IOException*/public void loadFromXML() throws FileNotFoundException, IOException {Properties properties = new Properties();properties.loadFromXML(new FileInputStream("middleware.xml"));Enumeration<Object> e = properties.keys();while(e.hasMoreElements()) {String key = (String) e.nextElement();System.out.println(key + ":" + properties.getProperty(key, ""));}}/*** Properties的setProperty和storeToXML方法儲(chǔ)存數(shù)據(jù)* @throws FileNotFoundException* @throws IOException*/public static void storeToXML() throws FileNotFoundException, IOException {Properties properties = new Properties();properties.setProperty("game", "unity");properties.setProperty("middleware", "c++");properties.setProperty("plantform1", "jni c++");properties.setProperty("plantform2", "oc c++");properties.storeToXML(new FileOutputStream("middleware.xml"), "game sdk middleware");}/*** Properties的getProperty和load方法加載數(shù)據(jù)* @throws FileNotFoundException* @throws IOException*/public void load() throws FileNotFoundException, IOException {Properties properties = new Properties();properties.load(new FileInputStream("people.properties"));Set<Object> set = properties.keySet();for (Object object : set) {System.out.println(object + ":" + properties.getProperty((String)object, ""));}}/*** Properties的setProperty和store方法儲(chǔ)存數(shù)據(jù)* @throws FileNotFoundException* @throws IOException*/public void store() throws FileNotFoundException, IOException {Properties properties = new Properties();properties.setProperty("name", "zhangsan");properties.setProperty("age", "22");properties.setProperty("sex", "male");properties.store(new FileOutputStream("people.properties"), "people infomation");}}?
總結(jié)
以上是生活随笔為你收集整理的044_Properties工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 042_JDK的Map接口
- 下一篇: 045_引用分类和WeakHashMap