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);
	}

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