Properties类
# 06.Properties类
在编写应用程序的时候,经常需要读写配置文件。
例如记录用户上次打开的文件,自动保存文件的时间间隔,使用什么主题等:
# 上次最后打开的文件:
last_open_file=/data/hello.txt
# 自动保存文件的时间间隔:
auto_save_interval=60
# 使用什么主题:
colorTheme=Monokai
2
3
4
5
6
我们使用的配置文件,其内容通常是key-value型的,我们完全可以用Map<String, String>
来存储和处理;但我们不用自己造轮子,Java集合库提供了一个Properties
来表示一组“配置”。
# 读取配置文件
Java默认配置文件以.properties
为扩展名,每行以key=value
表示,以#
课开头的是注释
我们自己手动创建一个配置文件setting.properties,然后再读取。
# setting.properties
last_open_file=/data/hello.txt
auto_save_interval=60
2
3
import java.io.FileInputStream;
import java.util.Properties;
public class IODemo8Properties {
public static void main(String[] args) throws Exception{
String filename = "setting.properties";
Properties props = new Properties();
props.load(new FileInputStream(filename));
String last_open_file = props.getProperty("last_open_file");
String auto_save_interval = props.getProperty("auto_save_interval");
System.out.println("last_open_file: " + last_open_file);
System.out.println("auto_save_interval: " + auto_save_interval);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
调用getProperty()
获取配置时,如果key不存在,将返回null
。我们还可以提供一个默认值,这样,当key不存在的时候,就返回默认值,语法格式为:public String getProperty(String key,String defaultValue)
,实践:
String testDefault = props.getProperty("testDefault", "aaa");
System.out.println("testDefault: " + testDefault); //aaa
2
用Properties
读取配置文件,一共有三步:
- 创建
Properties
实例; - 调用
load()
读取文件; - 调用
getProperty()
获取配置。
注意点:
- 如果有多个
.properties
文件,可以反复调用load()
读取,后读取的key-value会覆盖已读取的key-value。通过这种机制,我们可以先读取有默认的配置文件,然后读取用户自己的配置,这样就达到了用户的配置优先于默认配置的效果。 load(InputStream)
方法接收一个InputStream
实例,表示一个字节流,它不一定是文件流,还可以是ByteArrayInputStream等。
# 写入配置文件
如果通过setProperty()
修改了Properties
实例,可以把配置写入文件,以便下次启动时获得最新配置。写入配置文件使用store()
方法:
public void store(OutputStream out, String comments)throws IOException
第一个参数是OutputStream,第二个参数是本次存储配置时的注释(也会存储到配置文件里)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class IODemo8PropertiesWrite {
public static void main(String[] args) throws Exception{
String filename = "setting.properties";
Properties props = new Properties();
props.load(new FileInputStream(filename));
props.setProperty("myWebsite", "www.peterjxl.com");
props.store(new FileOutputStream(filename), "comment");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
运行后,配置文件内容如下:
#comment
#Mon Jan 30 22:42:33 CST 2023
myWebsite=www.peterjxl.com
auto_save_interval=60
last_open_file=/data/hello.txt
2
3
4
5
# 编码问题
早期版本的Java规定.properties
文件编码是ASCII编码(ISO8859-1),如果涉及到中文就必须用name=\u4e2d\u6587
来表示,非常别扭。从JDK9开始,Java的.properties
文件可以使用UTF-8编码了。
不过,需要注意的是,由于load(InputStream)
默认总是以ASCII编码读取字节流,所以会导致读到乱码。我们需要用另一个重载方法load(Reader)
读取:
Properties props = new Properties();
props.load(new FileReader("settings.properties", StandardCharsets.UTF_8));
2
就可以正常读取中文。InputStream
和Reader
的区别是一个是字节流,一个是字符流。字符流在内存中已经以char
类型表示了,不涉及编码问题。