properties類以及.properties文件的使用


1.關於Properties類

概述

 1.Properties作為Map使用

//      創建對象不可使用泛型
        Properties properties = new Properties();
//        存儲元素
        properties.put("張飛","18");
        properties.put("關羽","19");
        properties.put("劉備","20");
        Set<Object> objects = properties.keySet();
//        遍歷元素
        for (Object o:objects){
            System.out.println(o+":"+properties.get(o));
        }

 2.Properties作為Map使用的特有方法

//        setProperty​(String key, String value) 設置集合的鍵和值,都是String類型,調用 Hashtable方法 put 。
        Properties prop = new Properties();
        prop.setProperty("001","張飛");
/**
 *     public synchronized Object setProperty(String key, String value) {//注意學習這種設計方法
 *         return put(key, value);
 *     }
 *     public synchronized Object put(Object,Object){
 *          return map.put(Object,Object);
 *     }
 */
        prop.setProperty("002","關羽");
        prop.setProperty("003","劉備");
//        String getProperty​(String key) 使用此屬性列表中指定的鍵搜索屬性。
        System.out.println(prop.getProperty("001"));//張飛
//        Set<String> stringPropertyNames​() 從該屬性列表中返回一個不可修改的鍵集,其中鍵及其對應的值是字符串

        Set<String> strings = prop.stringPropertyNames();
        for (String s:strings){
            System.out.println(s+":"+prop.getProperty(s));
        }

.properties文件讀取方法匯總

方法1:Properties和IO相結合

 

 

  @Test
    public void testProperties() throws IOException {
        //讀取文件里面的內容
        Properties properties = new Properties();
        //下面的路徑我使用的是 Relative path(相對路徑) //src/test/Resources/dataBaseConfig.properties
        FileReader fileReader = new FileReader("src\\test\\Resources\\dataBaseConfig.properties");
        properties.load(fileReader);
        Set<String> strings = properties.stringPropertyNames();
        System.out.println(strings);//[jdbc.password, jdbc.username, jdbc.url, jdbc.driver]
        System.out.println(properties.getProperty("jdbc.driver"));//com.mysql.jdbc.Driver;
        //將內容寫到文件
        Properties properties2 = new Properties();
        FileWriter fileWriter = new FileWriter("src\\test\\Resources\\dataBaseConfig.properties",true);//第二個參數為true,追加寫入,不會覆蓋之前內容
        properties2.setProperty("配置參數1","值1");
        properties2.setProperty("配置參數2","值2");
        properties2.setProperty("配置參數3","值3");
        properties2.store(fileWriter,"注釋內容");
    }

方法2:ResourceBundle

 

 

    /**
     * ResourceBundle:
     * 1.可以用於讀取properties文件;
     * 2.只能讀取不能寫入
     * 3.只能讀取類路徑下的,不在類路徑下的無法讀取
     * */
    private static ResourceBundle resourceBundle=ResourceBundle.getBundle("config.bean");//參數指的是properties文件的位置,寫法是包名.文件名的方式
    public static void main(String[] args) {
        System.err.println(resourceBundle.getString("ACCOUNTERVICE"));//com.luzhanshi.learn.service.impl.IAccountServiceImplImpl
    }

 方法3:配合Spring注解:@Value獲取值

前提:

1.我們要提前創建了相應的配置文件:

 2.我們在spring的xml配置文件里面添加如下注解:

<!--    告知Spring,properties配置文件的位置-->
    <context:property-placeholder location="dataBaseConfig.properties"></context:property-placeholder>

3.使用如下方式獲取:

@Repository(value = "IAccountService_annotation")
public class IAccountService_annotationImpl implements IAccountService_annotation {
    @Value("https://www.hao123.com/")
    public String url;
    @Value("${jdbc.driver}")
    private String driver;
 @Override
    public void saveAccount() {
        System.out.println(url);//https://www.hao123.com/
        System.out.println(driver);//com.mysql.jdbc.Driver;
        iAccountDao_annotation.save();
    }
}

********************************************************************************************************************************************

spring純注解的情況下使用@value:

@Configuration//將該類聲明為spring配置類
@ComponentScan("spring")//配置掃描包
@PropertySource("dataBaseConfig.properties")//配置properties的路徑
public class AppTest {
...
}

聲明一個類,使用配置文件內容裝配變量值:

@Component("jdbc")
public class Jdbc {
    @Value("${jdbc.driver}")
    public String url;
}

獲取bean對象,打印值:

public class Test {
    public static void
    main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppTest.class);
        Jdbc jdbc = (Jdbc) context.getBean("jdbc");
        System.out.println(jdbc.url);//com.mysql.jdbc.Driver;
    }
}

方法4:讀取出來的內容直接轉為map

在很多項目中我們都會使用到.properties文件對我們的項目進行配置,今天就介紹一下.properties文件在項目中的使用:

如下圖,我們項目中有一個名為project.properties的properties文件 

從圖中可以看出,該文件配置了許多參數的默認值,那么我們在項目中如何引用它呢?:

首先我們書寫一個工具類ProjectUtils:

    /**
     * 傳入配置文件路徑,將其中屬性映射到Map中
     *
     * @param filepath
     * @return map
     */
    public  Map<String, String> getPropertiesValueMap(String filepath) {
        InputStreamReader isr = null;
        logger.info("接收到配置文件路徑是 filepath + " +filepath);
        Map<String, String> properties = new HashMap<>();
        if ("".equals(filepath)) {
            logger.info("傳入配置文件路徑不能為空!!");
            return properties;
        }
        try {
            Properties pro = new Properties();

            isr = new  InputStreamReader(getClass().getClassLoader()
                    .getResourceAsStream(filepath),"UTF-8");
            pro.load(isr);
            @SuppressWarnings("rawtypes")
                    Enumeration enu = pro.propertyNames();
            while (enu.hasMoreElements()) {
                String obj =(String) enu.nextElement();
                String objv = pro.getProperty(obj);
                properties.put(obj, objv);
            }
        } catch (Exception e) {
            properties.put("retCode","01");
            properties.put("retMsg","讀取配置文件失敗,請檢查配置文件");
            logger.info("解析配置文件失敗,請檢查配置文件是否正確!!,原因是:"+e.getMessage());
            return properties;
        }
        return properties;
    }

然后在需要獲取配置信息的地方調用上面我們封裝的方法(傳入配置文件的路徑):

        ProjectUtils pro = new ProjectUtils();
        Map<String ,String> map = pro.getPropertiesValueMap("project.properties");
        //System.out.println(map.get("440600"));
         int port =Integer.valueOf(map.get("port"));
        System.out.println(map.get("port"));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM