更新时间:2020-05-22 15:55:34 来源:动力节点 浏览2387次
properties文件是我们经常需要操作一种文件,它使用一种键值对的形式来保存属性集。
无论在学习上还是工作上经常需要读取,修改,删除properties文件里面的属性。
本文通过操作一个properties去认识怎样操作properties文件。
Java提供了Properties这个类Properties(Java.util.Properties),用于操作properties文件。
这是配置文件,file.properties
type=mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username=root
password=root
public class PropertiesDemo {
 
	public static final Properties p = new Properties();
	public static final String path = "file.properties";
初始化:
  /**
	 * 通过类装载器 初始化Properties
	 */
	public static void init() {
		//转换成流
	    InputStream inputStream =     
        PropertiesDemo.class.getClassLoader().getResourceAsStream(path);
		try {
			//从输入流中读取属性列表(键和元素对)
			p.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
获取:
 /**
	 * 通过key获取value
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		return p.getProperty(key);
	}
修改或者新增:
 /**
	 * 修改或者新增key
	 * @param key
	 * @param value
	 */
	public static void update(String key, String value) {
		p.setProperty(key, value);
		FileOutputStream oFile = null;
		try {
			oFile = new FileOutputStream(path);
			//将Properties中的属性列表(键和元素对)写入输出流
			p.store(oFile, "");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				oFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
删除:
 /**
	 * 通过key删除value
	 * @param key
	 */
	public static void delete(String key) {
		p.remove(key);
		FileOutputStream oFile = null;
		try {
			oFile = new FileOutputStream(path);
			p.store(oFile, "");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				oFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
获取所有:
  /**
	 * 循环所有key value
	 */
	public static void list() {
		Enumeration en = p.propertyNames(); //得到配置文件的名字
		while(en.hasMoreElements()) {
			String strKey = (String) en.nextElement();
			String strValue = p.getProperty(strKey);
			System.out.println(strKey + "=" + strValue);
		}
	}
测试:
public static void main(String[] args) {
	PropertiesDemo.init();
 
	//修改
	PropertiesDemo.update("password","123456");
	System.out.println(PropertiesDemo.get("password"));
 
	//删除
	PropertiesDemo.delete("username");
	System.out.println(PropertiesDemo.get("username"));
 
        //获取所有
	PropertiesDemo.list();
}

以上就是动力节点java培训机构的小编针对“编程技术分享,Java读取properties修改的文件”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。
						Java实验班
						0基础 0学费 15天面授
						Java就业班
						有基础 直达就业
						Java夜校直播班
						业余时间 高薪转行
						Java在职加薪班
						工作1~3年,加薪神器
						Java架构师班
						工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习