Java代碼操作properties配置文件(讀取,新增/修改,刪除)


項目中需要用到操作properties文件中的數據,記錄一下

package com.bonc.savepic.save;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author clj
 * @SinceDate 2019/3/26 17:05
 * @Description
 */
public class PropertiesUtil {

    /**
     * 獲取Properties對象
     * @return
     */
    public static Properties getProperties(){
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            //data.properties在resources目錄下
            inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("data.properties");
            properties.load(inputStream);
        } catch (FileNotFoundException e) {
            System.out.println("data.properties文件未找到!");
        } catch (IOException e) {
            System.out.println("出現IOException");
        } finally {
            try {
                if (null != inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                System.out.println("data.properties文件流關閉出現異常");
            }
        }
        return properties;
    }

    /**
     * 根據key查詢value值
     * @param key key
     * @return
     */
    public static String getValue(String key){
        Properties properties = getProperties();
        String value = properties.getProperty(key);
        return value;
    }

    /**
     * 新增/修改數據
     * @param key 
     * @param value
     */
    public static void setValue(String key, String value){
        Properties properties = getProperties();
        properties.setProperty(key, value);
        //此處獲取的路徑是target下classes

        //這里的path是項目文件的絕對路徑
        //先獲取項目絕對路徑:Thread.currentThread().getContextClassLoader().getResource("").getPath();
        //然后在項目路徑后面拼接"properties/sysConfig.properties";
        // 原注釋
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        path = path + "data.properties";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            properties.store(fileOutputStream, "注釋");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileOutputStream){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                System.out.println("data.properties文件流關閉出現異常");
            }
        }
    }

    /**
     * 刪除和修改只有語句不同
     * properties.remove(key);
     */
}

 轉載


免責聲明!

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



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