激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 基于Properties類操作.properties配置文件方法總結

基于Properties類操作.properties配置文件方法總結

2022-01-07 13:21那心之所向 Java教程

這篇文章主要介紹了Properties類操作.properties配置文件方法總結,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

一、properties文件

Properties文件是java中很常用的一種配置文件,文件后綴為“.properties”,屬文本文件,文件的內容格式是“鍵=值”的格式,可以用“#”作為注釋,java編程中用到的地方很多,運用配置文件,可以便于java深層次的解耦。

例如java應用通過JDBC連接數據庫時,可以把數據庫的配置寫在配置文件 jdbc.properties:

?
1
2
3
4
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/user
user=root
password=123456

這樣我們就可以通過加載properties配置文件來連接數據庫,達到深層次的解耦目的,如果想要換成oracle或是DB2,我們只需要修改配置文件即可,不用修改任何代碼就可以更換數據庫。

二、Properties類

java中提供了配置文件的操作類Properties類(java.util.Properties):

讀取properties文件的通用方法:根據鍵得到value

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
     * 讀取config.properties文件中的內容,放到Properties類中
     * @param filePath 文件路徑
     * @param key 配置文件中的key
     * @return 返回key對應的value
     */
    public static String readConfigFiles(String filePath,String key) {
        Properties prop = new Properties();
        try{
            InputStream inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
            inputStream.close();
            return prop.getProperty(key);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("未找到相關配置文件");
            return null;
        }
    }

把配置文件以鍵值對的形式存放到Map中:

?
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
/**
     * 把.properties文件中的鍵值對存放在Map中
     * @param inputStream 配置文件(inputstream形式傳入)
     * @return 返回Map
     */
    public Map<String, String> convertPropertityFileToMap(InputStream inputStream) {
        try {
            Properties prop = new Properties();
            Map<String, String> map = new HashMap<String, String>();
            if (inputStream != null) {
                prop.load(inputStream);
                Enumeration keyNames = prop.propertyNames();
                while (keyNames.hasMoreElements()) {
                    String key = (String) keyNames.nextElement();
                    String value = prop.getProperty(key);
                    map.put(key, value);
                }
                return map;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Properties類使用詳解

概述

Properties 繼承于 Hashtable。表示一個持久的屬性集,屬性列表以key-value的形式存在,key和value都是字符串。

Properties 類被許多Java類使用。例如,在獲取環境變量時它就作為System.getProperties()方法的返回值。

我們在很多需要避免硬編碼的應用場景下需要使用properties文件來加載程序需要的配置信息,比如JDBC、MyBatis框架等。Properties類則是properties文件和程序的中間橋梁,不論是從properties文件讀取信息還是寫入信息到properties文件都要經由Properties類。

常見方法

除了從Hashtable中所定義的方法,Properties定義了以下方法:

基于Properties類操作.properties配置文件方法總結

Properties類

下面我們從寫入、讀取、遍歷等角度來解析Properties類的常見用法:

寫入

Properties類調用setProperty方法將鍵值對保存到內存中,此時可以通過getProperty方法讀取,propertyNames方法進行遍歷,但是并沒有將鍵值對持久化到屬性文件中,故需要調用store方法持久化鍵值對到屬性文件中。

?
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
package cn.habitdiary;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import junit.framework.TestCase;
public class PropertiesTester extends TestCase {
    public void writeProperties() {
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream("config.properties");
            properties.setProperty("url", "jdbc:mysql://localhost:3306/");
            properties.setProperty("username", "root");
            properties.setProperty("password", "root");
            properties.setProperty("database", "users");//保存鍵值對到內存
            properties.store(output, "Steven1997 modify" + new Date().toString());
                        // 保存鍵值對到文件中
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

讀取

下面給出常見的六種讀取properties文件的方式:

?
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package cn.habitdiary;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
 * 讀取properties文件的方式
 *
 */
public class LoadPropertiesFileUtil {
    private static String basePath = "src/main/java/cn/habitdiary/prop.properties";
    private static String path = "";
    /**
     * 一、 使用java.util.Properties類的load(InputStream in)方法加載properties文件
     *
     * @return
     */
    public static String getPath1() {
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(
                    new File(basePath)));
            Properties prop = new Properties();
            prop.load(in);
            path = prop.getProperty("path");
        } catch (FileNotFoundException e) {
            System.out.println("properties文件路徑書寫有誤,請檢查!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    /**
     * 二、 使用java.util.ResourceBundle類的getBundle()方法
     * 注意:這個getBundle()方法的參數只能寫成包路徑+properties文件名,否則將拋異常
     *
     * @return
     */
    public static String getPath2() {
        ResourceBundle rb = ResourceBundle
                .getBundle("cn/habitdiary/prop");
        path = rb.getString("path");
        return path;
    }
    /**
     * 三、 使用java.util.PropertyResourceBundle類的構造函數
     *
     * @return
     */
    public static String getPath3() {
        InputStream in;
        try {
            in = new BufferedInputStream(new FileInputStream(basePath));
            ResourceBundle rb = new PropertyResourceBundle(in);
            path = rb.getString("path");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    /**
     * 四、 使用class變量的getResourceAsStream()方法
     * 注意:getResourceAsStream()方法的參數按格式寫到包路徑+properties文件名+.后綴
     *
     * @return
     */
    public static String getPath4() {
        InputStream in = LoadPropertiesFileUtil.class
                .getResourceAsStream("cn/habitdiary/prop.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            path = p.getProperty("path");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    /**
     * 五、
     * 使用class.getClassLoader()所得到的java.lang.ClassLoader的
     * getResourceAsStream()方法
     * getResourceAsStream(name)方法的參數必須是包路徑+文件名+.后綴
     * 否則會報空指針異常
     * @return
     */
    public static String getPath5() {
        InputStream in = LoadPropertiesFileUtil.class.getClassLoader()
                .getResourceAsStream("cn/habitdiary/prop.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            path = p.getProperty("path");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    /**
     * 六、 使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法
     * getSystemResourceAsStream()方法的參數格式也是有固定要求的
     *
     * @return
     */
    public static String getPath6() {
        InputStream in = ClassLoader
                .getSystemResourceAsStream("cn/habitdiary/prop.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            path = p.getProperty("path");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;
    }
    public static void main(String[] args) {
        System.out.println(LoadPropertiesFileUtil.getPath1());
        System.out.println(LoadPropertiesFileUtil.getPath2());
        System.out.println(LoadPropertiesFileUtil.getPath3());
        System.out.println(LoadPropertiesFileUtil.getPath4());
        System.out.println(LoadPropertiesFileUtil.getPath5());
        System.out.println(LoadPropertiesFileUtil.getPath6());
    }
}

其中第一、四、五、六種方式都是先獲得文件的輸入流,然后通過Properties類的load(InputStream inStream)方法加載到Properties對象中,最后通過Properties對象來操作文件內容。

第二、三中方式是通過ResourceBundle類來加載Properties文件,然后ResourceBundle對象來操做properties文件內容。

其中最重要的就是每種方式加載文件時,文件的路徑需要按照方法的定義的格式來加載,否則會拋出各種異常,比如空指針異常。

遍歷

下面給出四種遍歷Properties中的所有鍵值對的方法:

?
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
/**
     * 輸出properties的key和value
     */
    public static void printProp(Properties properties) {
        System.out.println("---------(方式一)------------");
        for (String key : properties.stringPropertyNames()) {
            System.out.println(key + "=" + properties.getProperty(key));
        }
        System.out.println("---------(方式二)------------");
        Set<Object> keys = properties.keySet();//返回屬性key的集合
        for (Object key : keys) {
            System.out.println(key.toString() + "=" + properties.get(key));
        }
        System.out.println("---------(方式三)------------");
        Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
        //返回的屬性鍵值對實體
        for (Map.Entry<Object, Object> entry : entrySet) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
        System.out.println("---------(方式四)------------");
        Enumeration<?> e = properties.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = properties.getProperty(key);
            System.out.println(key + "=" + value);
        }
    }

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://www.cnblogs.com/janson071/p/10082778.html

延伸 · 閱讀

精彩推薦
  • Java教程Java BufferWriter寫文件寫不進去或缺失數據的解決

    Java BufferWriter寫文件寫不進去或缺失數據的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進去或缺失數據的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程xml與Java對象的轉換詳解

    xml與Java對象的轉換詳解

    這篇文章主要介紹了xml與Java對象的轉換詳解的相關資料,需要的朋友可以參考下...

    Java教程網2942020-09-17
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關于小米推送Java代碼,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩中求8032021-07-12
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發現了對于集合操作轉換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關于Java8中S...

    阿杜7482021-02-04
  • Java教程Java實現搶紅包功能

    Java實現搶紅包功能

    這篇文章主要為大家詳細介紹了Java實現搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經有好久沒有升過級了。升級完畢重啟之后,突然發現好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
主站蜘蛛池模板: 色呦呦一区二区三区 | 黄色aaa视频 | 亚洲第一精品在线 | 日韩视频在线观看免费 | 91成人久久 | 精品国产乱码久久久久久丨区2区 | 成人一级黄色大片 | 久久99精品国产99久久6男男 | 国产在线中文 | 免费a视频 | 综合99 | 精品1 | 全网免费毛片 | 久久毛片 | 久久亚洲精选 | 91精品最新国内在线播放 | 日日狠狠久久偷偷四色综合免费 | 亚洲国产精品久久久久婷婷老年 | 黑人一级片视频 | 国产一区二区三区视频在线 | 欧洲精品久久久 | 99re久久最新地址获取 | 欧美亚洲一级 | 好看的91视频 | 国产一区二区在线免费播放 | 天天干天天碰 | 亚洲艳情网站 | 成人男男视频拍拍拍在线观看 | 护士hd老师fre0性xxx | 特片网久久 | 久久精品一二三区白丝高潮 | 久久久久久久久日本理论电影 | 成人在线视频精品 | 久久久www成人免费精品 | 久久99精品国产自在现线 | 精品一区二区久久久久 | 欧美中文字幕一区二区三区亚洲 | 色中色在线视频 | 在线观看国产网站 | 欧美激情性色生活片在线观看 | 国产九色在线观看 |