您好,欢迎来到爱go旅游网。
搜索
您的当前位置:首页java对properties文件的操作

java对properties文件的操作

来源:爱go旅游网
对properties文件的操作

1. 资源文件所存放的位置

资源文件妨碍classpath下,即工程项目的class包下

2. 获取系统资源文件的方式有2中

a. 通过 InputStream inputstream =

ClassLoader.getSystemResourceAsStream(\"info.properties\"); b. 通过 InputStream inputstream =

this.getClass().getResourceAsStream(\"/info.properties\");

采用第一种方式获取资源文件时,文件不以\"/\" 开头,而采用方法b的话,文件必须\"/\"开头

3. 提取加载资源文件的信息 Java代码

Properties properties = new Properties(); InputStream inputstream = ClassLoader.getSystemResourceAsStream(\"info.properties\"); // InputStream inputstream = this.getClass().getResourceAsStream(\"/info.properties\"); properties.load(inputstream);

4. 操作资源文件

a. 根据key值在资源文件中查询value值

1. getProperty(String key) 用指定的键在此属性列表中搜索属性。

2. getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。

b. 获取所有的键值对的信息 Java代码

Enumeration enumvalue = (Enumeration) properties.propertyNames();// 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键 while (enumvalue.hasMoreElements()) { String key = enumvalue.nextElement(); System.out.println(key + \" : \" + properties.getProperty(key)); }

c. 向资源文件中添加键值信息,如果key值相同就会将原有的信息覆盖 Java代码

URL url = ClassLoader.getSystemResource(\"info.properties\"); File file = new File(url.toURI()); InputStream is = new FileInputStream(file); properties.load(is); properties.setProperty(\"key\ OutputStream fos = new FileOutputStream(file); properties.store(fos, null); fos.flush(); is.close();

d. 删除相关的键值对 Java代码

File file = new File(ClassLoader.getSystemResource(\"info.properties\").toURI()); InputStream is = new FileInputStream(file); properties.load(is); properties.remove(\"key\"); OutputStream fos = new FileOutputStream(file); properties.store(fos, null); is.close(); fos.flush(); fos.close();File file = new File(ClassLoader.getSystemResource(\"info.properties\").toURI()); InputStream is = new FileInputStream(file); properties.load(is); properties.remove(\"key\"); OutputStream fos = new FileOutputStream(file); properties.store(fos, null); is.close(); fos.flush(); fos.close();

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务