【Java编程】写入、读取、遍历Properties文件
在Java开发中通常我们会存储配置參数信息到属性文件。这种属性文件能够是拥有键值对的属性文件,也能够是XML文件。关于XML文件的操作,请參考博文【Java编程】DOM XML Parser 解析、遍历、创建XML。
在该篇博文中,我将展示怎样向属性文件写入键值对。怎样读取属性文件里的键值对,怎样遍历属性文件。
1、向属性文件里写入键值对
特别注意:
Properties类调用setProperty方法将键值对保存到内存中。此时能够通过getProperty方法读取,propertyNames()方法进行遍历,可是并没有将键值对持久化到属性文件里。故须要调用store()方法持久化键值对到属性文件里。这里的store方法相似于Android SharedPreferences的commit()方法。
package com.andieguo.propertiesdemo;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import junit.framework.TestCase;
public class PropertiesTester extends TestCase {
public void writeProperties() {
Properties properties = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
properties.setProperty("url", "jdbc:mysql://localhost:3306/");
properties.setProperty("username", "root");
properties.setProperty("password", "root");
properties.setProperty("database", "bbs");//保存键值对到内存
properties.store(output, "andieguo modify" + new Date().toString());// 保存键值对到文件里
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行单元測试后。属性文件内容例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYW5kaWVfZ3Vv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
2、读取属性文件里的键值对
public class PropertiesTester extends TestCase {
public void loadProperties() {
Properties properties = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");//载入Java项目根路径下的配置文件
properties.load(input);// 载入属性文件
System.out.println("url:" + properties.getProperty("url"));
System.out.println("username:" + properties.getProperty("username"));
System.out.println("password:" + properties.getProperty("password"));
System.out.println("database:" + properties.getProperty("database"));
} catch (IOException io) {
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行单元測试方法。console输出的output例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYW5kaWVfZ3Vv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
3、遍历属性文件里的键值对
package com.andieguo.propertiesdemo;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import junit.framework.TestCase;
public class PropertiesTester extends TestCase {
public void printAll() {
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "config.properties";
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
//方法一:
Set<Object> keys = prop.keySet();//返回属性key的集合
for(Object key:keys){
System.out.println("key:"+key.toString()+",value:"+prop.get(key));
}
//方法二:
Set<Entry<Object, Object>> entrys = prop.entrySet();//返回的属性键值对实体
for(Entry<Object, Object> entry:entrys){
System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
}
//方法三:
Enumeration<?
> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key:" + key + ",Value:" + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4、其它方法
public void list(PrintStream out)
将属性列表输出到指定的输出流。此方法对调试非常实用。
public void storeToXML(OutputStream os,Stringcomment) throws IOException
发出一个表示此表中包括的全部属性的 XML 文档。
5、參考
Java Properties File Examples(推荐)
Java Property File example with write, read, load from Classpath and property xml file
6、你可能感兴趣的文章
【Java编程】写入、读取、遍历Properties文件的更多相关文章
- java如何读取和遍历properties文件
在java项目开发过程中,使用properties文件作为配置基本上是必不可少的,很多如系统配置信息,文件上传配置信息等等都是以这种方式进行保存.同时学会操作properties文件也是java基础. ...
- Java程序员的日常—— Properties文件的读写
在日常的Java程序开发中,Properties文件的读写是很常用的.经常有开发系统通过properties文件来当做配置文件,方便用户对系统参数进行调整. 那么本片就来简单的介绍下,如何使用Prop ...
- SpringBoot读取application.properties文件
http://blog.csdn.net/cloume/article/details/52538626 Spring Boot中使用自定义的properties Spring Boot的applic ...
- Java读取修改Properties文件
properties文件是我们经常需要操作一种文件,它使用一种键值对的形式来保存属性集. 无论在学习上还是工作上经常需要读取,修改,删除properties文件里面的属性. 本文通过操作一个prope ...
- Java编程的逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...
- ResourceBundle读取中文properties文件问题
昨天遇到一个问题,用ResourceBundle读取中文字符串资源文件时,死活读不出来. 一开始以为是文件路径不对,后来发现如果默认properties文件时英文就没问题.我的项目代码是在src目录下 ...
- SpringBoot读取配置文件(从classpath/file读取yml/properties文件)
一.读取properties文件 使用配置项@PropertySource 二.读取yml文件 启动类添加下面代码: @Bean public static PropertySourcesPlac ...
- java获取tomcat中的properties文件
System.getProperty("catalina.home") 获取tomcat的绝对路径 获取文件的绝对路径 在windous中拼接路径是" \ " ...
- java通过CLASSPATH读取包内文件
读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流:InputStream in = ReadFile.class.getResourceAsSt ...
随机推荐
- SysTick—系统定时器
本章参考资料<ARM Cortex™-M4F 技术参考手册> -4.5 章节 SysTick Timer(STK), 和4.48 章节 SHPRx,其中 STK 这个章节有 SysTick ...
- Android之2D图形(圆、直线、点)工具类 (持续更新)
public class Circle { private PointF centerPoint; private float radius; public PointF getCenterPoint ...
- php判断今日是本月的第几个星期几
php判断今日是本月的第几个星期几 php中有一个非常强悍的系统函数date()函数.巧妙的利用他可以实现显示任意我们需要的时间.比如今天遇到个需要是要判断今天是本月的第几个星期几,这里就不讨论这种说 ...
- 与HttpSessionListener接口有关的方法是。
与HttpSessionListener接口有关的方法是. A.sessionInitialized() B.sessionCreated() C.sessionFinialized() D.sess ...
- ARM汇编语言(3)(寄存器读写控制外设)
DAY4:ARM汇编(4) 一,GPIO编程 连接内存(二级cache),用来寻址:连接外设,用来控制: 1,GPIO,General-Purpose IO ports,通用输入输出端口, ...
- [转]C#自定义控件属性与行为
原文链接:http://blog.csdn.net/a237428367/article/details/5926445 控件应该定义属性而不是公共字段,因为可视化设计器在属性浏览器中显示属性,而不显 ...
- CAS SSO单点登录框架介绍
1.了解单点登录 SSO 主要特点是: SSO 应用之间使用 Web 协议(如 HTTPS) ,并且只有一个登录入口. SSO 的体系中有下面三种角色: 1) User(多个) 2) Web 应用( ...
- c++ new(不断跟新)
1.基础知识 /* 可以定义大小是0的数组,但不能引用,因为没有指向任何对象 new string[10]调用类的默认构造函数 new int[10]没有初始化,但new int[10]()会将数组初 ...
- sql 循环表中记录
=========================================================================循环排序查询数据=================== ...
- XMLHttpRequest 对象 status 和statusText 属性对照表
XMLHttpRequest 对象 status 和statusText 属性对照表 status statusText 说明 0** - 未被始化 1** - 请求收到,继续处理 100 Conti ...