java.util.Properties

sayWhat_sayHello發表於2018-08-13

在學習資料庫知識的時候偶然看到這個類,而平時可能根本不會接觸到。但是Properties作為常用的配置,瞭解一下其原理還是不錯的~

首先是新建一個例項物件:

Properties properties = new Properties();

然後從檔案中載入

try(InputStream inputStream = Files.newInputStream(Paths.get("C:\\Users\\dell-pc\\IdeaProjects\\FreedomTest\\src\\main\\java\\random\\message.properties"))){
            properties.load(inputStream);
        }//這裡我用的是絕對路徑,若要引用程式碼請修改路徑
        System.out.println(properties.getProperty("id"));}

接著就是方法的呼叫,主要有:
String getProperty(String key, String defaultValue)) : 獲取key的值,如果沒有則使用defaultValue

Set<> stringPropertyNames():獲取所有key的名字,以set儲存

Enumeration


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;

public class PropertiesTest {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        try(InputStream inputStream = Files.newInputStream(Paths.get("C:\\Users\\dell-pc\\IdeaProjects\\FreedomTest\\src\\main\\java\\random\\message.properties"))){
            properties.load(inputStream);
        }//這裡我用的是絕對路徑,若要引用程式碼請修改路徑
        System.out.println(properties.getProperty("id"));
        System.out.println(properties.getProperty("message"));
        System.out.println(properties.getProperty("ok", "5"));
        Set<String> strings = properties.stringPropertyNames();
        strings.forEach(s->System.out.println(s));

        Enumeration<?> enumeration = properties.propertyNames();
        while(enumeration.hasMoreElements()){
            System.out.println(enumeration.nextElement());
        }

        properties.list(System.out);

        try(FileOutputStream fileOutputStream = new FileOutputStream("output.txt")){
            try(PrintStream printStream = new PrintStream(fileOutputStream)) {
                properties.list(printStream);
                properties.store(fileOutputStream, "output");
                properties.storeToXML(fileOutputStream,"xml","utf-8");
            }
        }


    }
}

message.properties檔案:

id = 1
message = "hello"
name = "5"

執行結果:

1
"hello"
5
name
message
id
name
message
id
-- listing properties --
name="5"
message="hello"
id=1