本篇文章为大家展示了如何使用Java实现操作 Properties 文件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Java 对 Properties 文件的操作
简介
在 Java 中,我们常用 java.util.Properties.Properties 类来解析 Properties 文件,Properties 格式文件是 Java 常用的配置文件,它用来在文件中存储键-值对,其中键和值用等号分隔,格式如下:
name=shawearn
Properties 类是 java.util.Hashtable<Object, Object> 的子类,用于键和值之间的映射。
在对 Properties 格式文件的操作中,我们常使用 Properties 类的一下方法:
Properties():用于创建一个无任何属性值 Properties 对象;
写入 Properties 文件:
// 创建一个 Properties 实例;
Properties p = new Properties();
// 为 Properties 设置属性及属性值;
p.setProperty("name", "shawearn");
p.setProperty("address", "XX 省 XX 市");
// 保存 Properties 到 shawearn.properties 文件中;
FileOutputStream out = new FileOutputStream("shawearn.properties");
p.store(out, "Create by Shawearn!");
out.close();
读取 Properties 文件:
// 创建一个 Properties 实例;
Properties p = new Properties();
// 读取配置文件;
FileInputStream in = new FileInputStream("shawearn.properties");
// 加载配置文件到 Properties 实例中;
p.load(in);
in.close();
最后附上测试代码:
package com.shawearn.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
/**
* @author Shawearn
*
*/
public class TestProperties {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
TestProperties t = new TestProperties();
// 测试写入;
t.testWrite();
// 测试读取;
t.testRead();
}
/*
* 测试对 Properties 文件的写入操作;
*/
private void testWrite() throws IOException {
// 创建一个 Properties 实例;
Properties p = new Properties();
// 为 Properties 设置属性及属性值;
p.setProperty("name", "shawearn");
p.setProperty("address", "XX 省 XX 市");
// 保存 Properties 到 shawearn.properties 文件中;
FileOutputStream out = new FileOutputStream("shawearn.properties");
p.store(out, "Create by Shawearn!");
out.close();
System.out.println("写入成功!");
}
/*
* 测试对 Properties 文件的读取操作;
*/
private void testRead() throws IOException {
// 创建一个 Properties 实例;
Properties p = new Properties();
// 读取配置文件;
FileInputStream in = new FileInputStream("shawearn.properties");
// 加载配置文件到 Properties 实例中;
p.load(in);
in.close();
// 获取 Properties 文件中所有的 key;
Set<String> keys = p.stringPropertyNames();
// 遍历所有的 key;
for (String key : keys) {
// 获取 Properties 文件中 key 所对应的 value;
Object value = p.get(key);
// 输入 key 和对应的 value;
System.out.println(key + " => " + value);
}
}
}
控制台输出结果:
address => XX 省 XX 市
name => shawearn
shawearn.properties 文件内容:
#Create by Shawearn!
#Thu Nov 19 12:43:41 CST 2015
name=shawearn
address=XX \u7701 XX \u5E02
上述内容就是如何使用Java实现操作 Properties 文件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。