最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2021年09月17日 15:24:28   作者:那心之所向  
這篇文章主要介紹了Properties類操作.properties配置文件方法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、properties文件

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

例如java應(yīng)用通過JDBC連接數(shù)據(jù)庫(kù)時(shí),可以把數(shù)據(jù)庫(kù)的配置寫在配置文件 jdbc.properties:

driver=com.mysql.jdbc.Driver 
jdbcUrl=jdbc:mysql://localhost:3306/user 
user=root 
password=123456

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

二、Properties類

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

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

/**
     * 讀取config.properties文件中的內(nèi)容,放到Properties類中
     * @param filePath 文件路徑
     * @param key 配置文件中的key
     * @return 返回key對(duì)應(yīng)的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("未找到相關(guān)配置文件");
            return null;
        }
    }

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

/**
     * 把.properties文件中的鍵值對(duì)存放在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。表示一個(gè)持久的屬性集,屬性列表以key-value的形式存在,key和value都是字符串。

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

我們?cè)诤芏嘈枰苊庥簿幋a的應(yīng)用場(chǎng)景下需要使用properties文件來(lái)加載程序需要的配置信息,比如JDBC、MyBatis框架等。Properties類則是properties文件和程序的中間橋梁,不論是從properties文件讀取信息還是寫入信息到properties文件都要經(jīng)由Properties類。

常見方法

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

Properties類

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

寫入

Properties類調(diào)用setProperty方法將鍵值對(duì)保存到內(nèi)存中,此時(shí)可以通過getProperty方法讀取,propertyNames方法進(jìn)行遍歷,但是并沒有將鍵值對(duì)持久化到屬性文件中,故需要調(diào)用store方法持久化鍵值對(duì)到屬性文件中。

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");//保存鍵值對(duì)到內(nèi)存
            properties.store(output, "Steven1997 modify" + new Date().toString());
                        // 保存鍵值對(duì)到文件中
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

讀取

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

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文件路徑書寫有誤,請(qǐng)檢查!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
    /**
     * 二、 使用java.util.ResourceBundle類的getBundle()方法
     * 注意:這個(gè)getBundle()方法的參數(shù)只能寫成包路徑+properties文件名,否則將拋異常
     *
     * @return
     */
    public static String getPath2() {
        ResourceBundle rb = ResourceBundle
                .getBundle("cn/habitdiary/prop");
        path = rb.getString("path");
        return path;
    }
    /**
     * 三、 使用java.util.PropertyResourceBundle類的構(gòu)造函數(shù)
     *
     * @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()方法的參數(shù)按格式寫到包路徑+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)方法的參數(shù)必須是包路徑+文件名+.后綴
     * 否則會(huì)報(bào)空指針異常
     * @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()靜態(tài)方法
     * getSystemResourceAsStream()方法的參數(shù)格式也是有固定要求的
     *
     * @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對(duì)象中,最后通過Properties對(duì)象來(lái)操作文件內(nèi)容。

第二、三中方式是通過ResourceBundle類來(lái)加載Properties文件,然后ResourceBundle對(duì)象來(lái)操做properties文件內(nèi)容。

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

遍歷

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

/**
     * 輸出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();
        //返回的屬性鍵值對(duì)實(shí)體
        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);
        }
    }

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot使用@Cacheable注解實(shí)現(xiàn)數(shù)據(jù)緩存

    Springboot使用@Cacheable注解實(shí)現(xiàn)數(shù)據(jù)緩存

    本文介紹如何在Springboot中通過@Cacheable注解實(shí)現(xiàn)數(shù)據(jù)緩存,在每次調(diào)用添加了@Cacheable注解的方法時(shí),Spring 會(huì)檢查指定參數(shù)的指定目標(biāo)方法是否已經(jīng)被調(diào)用過,文中有詳細(xì)的代碼示例,需要的朋友可以參考下
    2023-10-10
  • java 簡(jiǎn)單的計(jì)算器程序?qū)嵗a

    java 簡(jiǎn)單的計(jì)算器程序?qū)嵗a

    這篇文章主要介紹了java 簡(jiǎn)單的計(jì)算器程序?qū)嵗a的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • idea中定時(shí)及多數(shù)據(jù)源配置方法

    idea中定時(shí)及多數(shù)據(jù)源配置方法

    因項(xiàng)目要求,需要定時(shí)從達(dá)夢(mèng)數(shù)據(jù)庫(kù)中取數(shù)據(jù),并插入或更新到ORACLE數(shù)據(jù)庫(kù)中,這篇文章主要介紹了idea中定時(shí)及多數(shù)據(jù)源配置方法,需要的朋友可以參考下
    2023-12-12
  • 淺析Java進(jìn)制轉(zhuǎn)換、輸入、命名問題

    淺析Java進(jìn)制轉(zhuǎn)換、輸入、命名問題

    這篇文章主要介紹了Java進(jìn)制轉(zhuǎn)換、輸入、命名問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • 關(guān)于Spring源碼深度解析(AOP功能源碼解析)

    關(guān)于Spring源碼深度解析(AOP功能源碼解析)

    這篇文章主要介紹了關(guān)于Spring源碼深度解析(AOP功能源碼解析),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • springboot項(xiàng)目中mapper.xml文件找不到的三種解決方案

    springboot項(xiàng)目中mapper.xml文件找不到的三種解決方案

    這篇文章主要介紹了springboot項(xiàng)目中mapper.xml文件找不到的三種解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Java數(shù)據(jù)結(jié)構(gòu)貪心算法的實(shí)現(xiàn)

    Java數(shù)據(jù)結(jié)構(gòu)貪心算法的實(shí)現(xiàn)

    本文主要介紹了Java數(shù)據(jù)結(jié)構(gòu)貪心算法的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2007-03-03
  • 使用Spark?SQL實(shí)現(xiàn)讀取不帶表頭的txt文件

    使用Spark?SQL實(shí)現(xiàn)讀取不帶表頭的txt文件

    這篇文章主要為大家詳細(xì)介紹了如何使用Spark?SQL實(shí)現(xiàn)讀取不帶表頭的txt文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • java.lang.IllegalArgumentException:Invalid character found異常解決

    java.lang.IllegalArgumentException:Invalid character&nb

    本文介紹了java.lang.IllegalArgumentException: Invalid character found異常的解決,方法包括檢查代碼中的方法名,使用合適的HTTP請(qǐng)求方法常量,使用第三方HTTP庫(kù),檢查請(qǐng)求URL以及使用調(diào)試和日志工具,通過這些方法,我們可以解決異常并確保網(wǎng)絡(luò)應(yīng)用程序的正常運(yùn)行
    2023-10-10
  • springboot中將日志信息存儲(chǔ)在catalina.base中過程解析

    springboot中將日志信息存儲(chǔ)在catalina.base中過程解析

    這篇文章主要介紹了springboot中將日志信息存儲(chǔ)在catalina.base中過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09

最新評(píng)論

临城县| 临海市| 响水县| 博兴县| 黄梅县| 宜黄县| 屯门区| 梁山县| 革吉县| 濮阳市| 兴安盟| 靖边县| 奉新县| 雅安市| 顺昌县| 定安县| 永安市| 广元市| 仁化县| 张家川| 华蓥市| 平度市| 浮山县| 双城市| 凤翔县| 冕宁县| 崇文区| 西贡区| 金堂县| 新民市| 武汉市| 襄樊市| 广西| 黔西| 景泰县| 绥江县| 锡林浩特市| 北安市| 韶山市| 东丰县| 班戈县|