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);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 while (enumvalue.hasMoreElements()) { String key = enumvalue.nextElement(); System.out.println(key + " : " + properties.getProperty(key)); } Enumeration 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", "value"); OutputStream fos = new FileOutputStream(file); properties.store(fos, null); fos.flush(); is.close();URL url = ClassLoader.getSystemResource("info.properties"); File file = new File(url.toURI()); InputStream is = new FileInputStream(file); properties.load(is); properties.setProperty("key", "value"); 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();