java怎麼讀取properties文件、修改properties文件和封裝properties

什麼是Properties文件,Properties文件和XML一樣是java中經常使用到的一種配置文件,讀取和使用起來比較方便,並且可讀性好。我們在編寫代碼的過程中爲了將代碼提高可參數化經常會將一些配置屬性存放在我們的配置文件中,例如JDBC的URL、用戶名、密碼等甚至一些文件路徑或者是一些常用的參數。這樣我們當數據庫發生改變的時候就不需要改原有的代碼了。
Properties文件的特點就是Key=value的形式存儲參數。類似於Java中的HashMap。

1、通過Properties對象加載讀取Properties文件
在日常的編寫代碼中我們用的最多的操作Properties文件就是讀的操作。很少會有寫的操作,所以讀是重點內容。

這是我們準備好的一個簡單的配置文件裏面屬性有兩個
user=admin
passWd=123456
在這裏插入圖片描述
準備好了之後我們開始編寫讀取的代碼

package com.lqs.softly.auto.test;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {

    @Test
    public void readProperties() throws Exception{
        //新建一個文件對象
        File propertiesFile=new File("/Users/zq/workSpase/softlyAuto/resources/config/demo.properties");
        //新建一個properties對象
        Properties properties=new Properties();
        //將文件放到文件輸入流
        FileInputStream propertiesInputStream=new FileInputStream(propertiesFile);
        //使用properties對象加載文件輸入流
        properties.load(propertiesInputStream);
        //輸出
        System.out.println(properties.getProperty("user")  );
        System.out.println(properties.getProperty("passWd")  );
    }
}

在這裏插入圖片描述
2、通過轉化程Map來讀取Properties文件
之前我們就說過Properties文件和Java中的map類似,其實Properties文件你可以將他看作java中一種比較老的一種類型HashTable
一、hashMap 與 HashTable 的區別
1、主要:
HashTable線程安全,同步,效率低下
HashMap線程不安全,不同步,效率高
2、父類:
HashTable 是Dictionary HashMap是AbstractMap
3、null:
HashTable鍵與值不能爲null
詳細區別內容:https://blog.csdn.net/weixin_44019406/article/details/98945137(個人認爲這篇文章寫的不錯)

@Test
public void propertiesToMap() throws Exception{
    FileInputStream in = null;
    //新建一個properties對象
    Properties ps = new Properties();
    //新建一個文件對象
    File propertiesFile = new File("/Users/zq/workSpase/softlyAuto/resources/config/demo.properties");
    //將文件放到文件輸入流
    in = new FileInputStream(propertiesFile);
    //使用properties對象加載文件輸入流
    ps.load(in);
    //將得到的Properties對象轉換成hashMap
    Map<String, String> wen = new HashMap<String, String>((Map) ps);
    System.out.println(wen.get("user")  );
    System.out.println(wen.get("passWd")  );
}

在這裏插入圖片描述

3、至於修改properties配置文件作者就不強調了一般來說對於Java開發都不會去使用代碼去修改properties配置文件的,一般都是手動修改。除非個例。
注意:前面的代碼相信有些細心的人就發現了,說我沒有將輸入流關閉,的確上面確實偷懶了。上面的代碼只是教你基本使用,而正確使用是將其封裝成我們需要的Utils包,也就是我們的工具包,怎麼封裝呢。無非就是讀和寫對吧。還有需要做一些異常處理使代碼更加的穩固。
代碼僅供參考:

package com.lqs.softly.auto.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class PropertiesUtils {

	private static Properties ps = new Properties();
	private static String proPath = null;
	private static Map<String, String> proLoadMap = null;

	public PropertiesUtils(String path) {
		// TODO Auto-generated constructor stub
		proPath = path;
		proLoadMap = getPropertiesMap(path);
	}

	public PropertiesUtils() {

	}

	/**
	 * 獲取文件的values值
	 * 
	 * @param filePath
	 * @param key
	 * @return
	 */
	public static String getPropertiesValue(String filePath, String key) {
		if (null != filePath) {
			String value = null;
			File propertiesFile = new File(filePath);
			if (!propertiesFile.exists()) {
				return null;
			}
			Properties properties = new Properties();
			FileInputStream propertiesInputStream = null;
			try {
				propertiesInputStream = new FileInputStream(propertiesFile);
				properties.load(propertiesInputStream);
				value = properties.getProperty(key).trim();
//				System.err.println(value);
				propertiesInputStream.close();
			} catch (Exception e) {
//				 TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (null != propertiesInputStream)
						propertiesInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (value.isEmpty())
				return null;
			return value;

		} else {
			return null;
		}

	}

	/**
	 * 設置properties文件k,v
	 * 
	 * @param filePath
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean setProertiesConf(String filePath, String key, String value) {
		if (null != filePath && null != key && null != value && !key.equals("") && !value.equals("")) {
			FileOutputStream out = null;
			try {
				PropertiesUtils properties = new PropertiesUtils(filePath);
				@SuppressWarnings("static-access")
				Map<String, String> wen = properties.getPropertiesMap(filePath);
				wen.put(key, value);

				for (Map.Entry<String, String> entry : wen.entrySet()) {
					ps.setProperty(entry.getKey(), entry.getValue());
				}
				File propertiesFile = new File(filePath);
				if (!propertiesFile.exists()) {
					return false;
				}
				out = new FileOutputStream(propertiesFile);
				ps.store(out, null);
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				return false;

			} finally {
				if (null != out) {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		} else {
			return false;

		}

	}

	@SuppressWarnings("unused")
	private static boolean mapToProperties(Map<?,?> map) {
		FileOutputStream out = null;
		for (Map.Entry<String, String> entry : proLoadMap.entrySet()) {
			ps.setProperty(entry.getKey(), entry.getValue());
		}
		File propertiesFile = new File(proPath);
		if (!propertiesFile.exists()) {
			return false;
		}
		try {		
			out = new FileOutputStream(propertiesFile);	
			ps.store(out, null);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return false;
		}finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 將properties配置文件轉換城map格式
	 * 
	 * @param propertiesFilePath
	 * @return Map<String, String>
	 */

	@SuppressWarnings("rawtypes")
	public static Map<String, String> getPropertiesMap(String propertiesFilePath) {

		FileInputStream in = null;
		File propertiesFile = new File(propertiesFilePath);
		if (!propertiesFile.exists()) {
			return null;
		}

		try {
			in = new FileInputStream(propertiesFile);
			ps.load(in);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.getMessage();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		@SuppressWarnings("unchecked")
		Map<String, String> wen = new HashMap<String, String>((Map) ps);

		return wen;
	}

	/**
	 * 獲取加載好的Properties的Value值
	 * 
	 * @param key
	 * @return String
	 */
	public  String getDefaultPropertiesValue(String key) {
		if (null != proLoadMap) {
			return proLoadMap.get(key);
		}
		return null;

	}

	/**
	 * 獲取加載好的Properties的所有Key
	 * 
	 * @return Set<String>
	 */
	public  Set<String> getDefaultKeys() {
		if (null != proLoadMap) {
			return proLoadMap.keySet();
		}
		return null;
	}

	/**
	 * 設置已經加載好文件的K和V值
	 * 
	 * @param key
	 * @param value
	 * @return boolean true:成功 false:失敗
	 */
	public  boolean put(String key, String value) {
		boolean TF = setProertiesConf(proPath, key, value);
		proLoadMap = getPropertiesMap(proPath);
		return TF;
	}

	public  Properties getDefaultPs() {
		return ps;
	}

	public  String getDefaultProPath() {
		return proPath;
	}

	public  Map<String, String> updateDefaultProPath(String proPath) {
		PropertiesUtils.proPath = proPath;
		return proLoadMap = getPropertiesMap(proPath);
	}

	public  Map<String, String> getDefaultProLoadMap() {
		return proLoadMap;
	}

	public  void setDefaultProLoadMap(Map<String, String> map) {
		proLoadMap = map;
	}
	
	public  boolean Commit(Map<String, String> map) {
		return mapToProperties(proLoadMap);
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章