一.properties簡介
properties 類繼承自hashtable,提供的方法很像map的實現類hashmap。它在 java 編程的早期就有了,并且幾乎沒有什么變化。j2se 的 tiger 版本增強了這個類,不僅可以用它在單獨一行中指定用等號分隔的多個鍵-值對(其中鍵和值是用等號分隔的),還可以用xml 文件裝載和保存這些鍵-值對。
二.properties 的加載和簡單的使用
1.路徑存放
2.信息配置
1
2
|
name = lily age = 22 |
3.簡單的加載和使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package com.my.utils; import java.io.ioexception; import java.io.inputstream; import java.util.properties; public class loadprop { public static void main(string[] args) { // todo auto-generated method stub properties prop = new properties(); inputstream in = loadprop. class .getclassloader().getresourceasstream( "config/prop.properties" ); try { prop.load(in); system.out.println(prop.get( "name" )); prop.setproperty( "name" , "lucy" ); system.out.println(prop.get( "name" )); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } finally { try { in.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } } |
4.使用 java.util.enumeration 獲取所有key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package com.my.utils; import java.io.ioexception; import java.io.inputstream; import java.util.enumeration; import java.util.properties; public class loadprop { @suppresswarnings ( "unchecked" ) public static void main(string[] args) { // todo auto-generated method stub properties prop = new properties(); inputstream in = loadprop. class .getclassloader().getresourceasstream( "config/prop.properties" ); enumeration<string> en = null ; string key = null ; try { prop.load(in); en = (enumeration<string>) prop.propertynames(); while (en.hasmoreelements()) { key = (string) en.nextelement(); system.out.println(key); } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } finally { try { in.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/lukelook/p/8660418.html