java中Properties理解
阿新 • • 發佈:2019-01-04
屬性物件是雜湊表的子類
不像地圖鍵值對設定鍵和值的屬性;
例如:定義地圖需要
Map<string,string> map=new Map <string,string>();
而化子性質直接定義物件,且他的鍵和值都是字串型別的
Properties prop=new Properties();
1.設定鍵值對
例如
prop.setProperty("123", "222"); prop.setProperty("789", "111"); prop.setProperty("456", "123");
2.讀取鍵值對
prop.getProperty("123");
prop.getProperty("789");
prop.getProperty("456");
3.儲存檔案的兩種方法
-
-
void
list(PrintStream out)
將此屬性列表列印到指定的輸出流。
void
list
-
-
void
store(OutputStream out, String comments)
將此屬性列表(鍵和元素對)此寫入
Properties
表中,適合以於使用load(InputStream)
方法載入到Properties
表中的格式輸出流。void
store
將此屬性列表(鍵和元素對)此寫入
Properties
表中,適合以使用load(Reader)
方法的格式輸出到輸出字元流。
-
-
public static void WriterProperties() {
Properties prop=new Properties();
prop.setProperty("123", "222");
prop.setProperty("789", "111");
prop.setProperty("456", "123");
Writer writer=null;
try {
/**
* list方法與store的方法區別
* list:帶預設的註釋,且提供printwriter和PrintStream兩種方式寫入
* store:自定義註釋,且檔案寫入的時候寫入了時間,提供OutputStream,Writer兩種方法寫入
*/
//list方法
//PrintWriter pWriter=new PrintWriter(new FileWriter("prop.txt"));
//PrintStream pStream=new PrintStream(new FileOutputStream("1.txt"));
//prop.list(pStream);
//store方法
//OutputStream oStream=new FileOutputStream("1.txt",true);
writer=new FileWriter("prop.txt",true);
prop.store(writer, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4.讀取檔案中的屬性中的值
一.load方法
-
-
void
load(InputStream inStream)
從輸入位元組流讀取屬性列表(鍵和元素對)。
void
load(Reader reader)
以簡單的線性格式從輸入字元流讀取屬性列表(關鍵字和元素對)。
-
public static void readerProperties() {
Properties prop=new Properties();
InputStream inStream=null;
//Reader reader=null;
try {
//建立一個讀檔案的物件
//reader=new FileReader("prop.txt");
inStream = new FileInputStream("porp.tst");
//load方法是將檔案的properties物件讀到流中
prop.load(inStream);
//取properties中的key集合
Set<Object> key=prop.keySet();
//遍歷set集合
for (Object object : key) {
String kString=(String) object;
System.out.println(prop.getProperty(kString));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (inStream!=null) {
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}