java读写Properties属性文件

2016-06-05 1647点热度 0条评论

Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。像Python支持的配置文件是.ini文件,同样,它也有自己读取配置文件的类ConfigParse,方便程序员或用户通过该类的方法来修改.ini配置文件。在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

它提供了几个主要的方法:

  1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
  2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
  3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
  4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
  5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
package clibrary;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class PropertiesUtil {
	private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

	/**
	 * 读取配置文件某属性
	 */
	public String readValue(String filePath, String key) {
		Properties props = new Properties();

		if (!filePath.startsWith("/")) {
			filePath = "/" + filePath;
		}

		try {
			InputStream inputStream = this.getClass().getResourceAsStream(filePath);
			props.load(inputStream);
		} catch (NullPointerException e) {
			logger.warn("文件不存在!");
		} catch (IOException e) {
			logger.warn(e.getMessage() + "文件流错误");
		}

		return props.getProperty(key);

	}

	/**
	 * 打印配置文件全部内容(filePath,配置文件名,如果有路径,props/test.properties)
	 */
	public void readProperties(String filePath) {
		Properties props = new Properties();
		try {
			// 注意路径以 / 开始,没有则处理
			if (!filePath.startsWith("/"))
				filePath = "/" + filePath;
			InputStream in = this.getClass().getResourceAsStream(filePath);
			props.load(in);

			props.forEach((key, value) -> logger.debug("Key = {}, Value = {}", key, value));

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	/**
	 * 将值写入配置文件
	 */
	public void writeProperties(String fileName, String parameterName, String parameterValue) {
		if (!fileName.startsWith("/"))
			fileName = "/" + fileName;
		FileOutputStream outputStream = null;
		Properties pps = new Properties();

		try {
			pps.load(this.getClass().getResourceAsStream(fileName));

			pps.setProperty(parameterName, parameterValue);
			outputStream = new FileOutputStream("src/main/resources/jdbc.properties");
			pps.store(outputStream, null);
		} catch (IOException e) {
			logger.warn(e.getMessage());
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.getMessage();
				}
			}
		}
	}
}

测试类

package clibrary;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.LocalTime;

import static org.junit.Assert.*;

public class PropertiesUtilTest {

	private Logger logger = LoggerFactory.getLogger(getClass());
	PropertiesUtil propertiesUtil = null;

	@Before
	public void init(){
		propertiesUtil = new PropertiesUtil();
	}

	@Test
	public void testReadValue(){
		String minIdle = propertiesUtil.readValue("jdbc.properties", "minIdle");
		assertEquals("5",minIdle);
		logger.debug(minIdle);
	}

	@Test
	public void testReadProperties(){
		propertiesUtil.readProperties("jdbc.properties");
	}

	@Test
	public void testWriteProperties(){
		propertiesUtil.writeProperties("jdbc.properties","Jalena","19");
	}

	@Test
	public void showTime(){
		logger.debug(LocalTime.now().toString());
		logger.debug(LocalDateTime.now().toString());
	}

}

Jalena

原创内容,转载请注明出处! 部分内容来自网络,请遵守法律适用!

文章评论