在java中有一种属性文件(资源文件)的定义:*.properties
文件,在这种文件里面其内容的保存形式为 “key = value
” ,通过ResourceBundle
类读取的时候只能读取内容,要想编辑其内容则需要通过Properties
类来完成,这个类是专门做属性处理的。
properties类的定义:
//继承自Hashtable类
public class Properties extends Hashtable<Object,Object>
1. 属性基本操作
- 这个类里的方法有:
① 设置属性:setProperty(String key, String value)
② 取得属性:getProperty(String key)
,如果没有指定的key则返回null
③ 取得属性:getProperty(String key, String defaultValue)
,如果没有指定的key则返回默认值
④ 获得属性列表:list(PrintStream out)
package com.xxx;
import java.util.Properties;
public class TestProperties {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("Java", "Java is best");
properties.setProperty("C++", "C++ is best too");
System.out.println(properties.getProperty("Java"));
System.out.println(properties.getProperty("JavaScript"));
System.out.println(properties.getProperty("JavaScript", "JavaScript is best"));
properties.list(System.out);
}
}
2. 属性和文件的操作
- 在
Properties
类中提供有I/O
支持的方法:
① 属性保存到文件中:store(OutputStream out, String comments)
② 从文件中读取属性:load(InputStream inStream)
package com.xxx;
import java.io.*;
import java.util.Properties;
public class TestProperties {
public static void main(String[] args) {
Properties properties = new Properties();
//Properties对象关联到.properties文件
String messageFile = "D:\\java\\IDEA\\集合框架\\src\\com\\bittech\\message.properties";
try(Reader reader = new FileReader(messageFile)) {
properties.load(reader);
properties.list(System.out);
System.out.println("==========");
System.out.println(properties.getProperty("c"));
System.out.println(properties.getProperty("javascript", "JavaScript语言非常重要!"));
System.out.println(properties.size());
//修改Properties对象
properties.setProperty("javascript", "JavaScript很重要");
properties.setProperty("c", "c语言不简单");
System.out.println("==========");
properties.list(System.out);
try (FileWriter writer = new FileWriter(messageFile)) {
properties.store(writer, "修改内容");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//message.properties文件的内容:
#修改内容
#Sun Apr 21 11:28:12 CST 2019
javascript=JavaScript很重要
java=Java is best
c=c语言不简单