【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 ...
随机推荐
- git patch生成方法
先把改动commit掉,然后生产改动patch给提交代码的同事,详细操作过程例如以下: 改动代码的同事: git format-patch al821_xxx origin/al821_xxx 会生成 ...
- matlab hornerDemo
% a quick demo of Horner's method and its effects clear all close all % first a comparison of ways t ...
- Yii2 Api认证和授权(翻译)
Authentication 认证 RESTful Api 是无状态的, 因此这意味着不能使用 sessions && cookies. 因此每一个请求应该带有一些 authentic ...
- bzoj2005 能量采集 莫比乌斯或者普通容斥
/** 题目:bzoj2005 能量采集 链接:https://vjudge.net/contest/178455#problem/F 题意:栋栋有一块长方形的地,他在地上种了一种能量植物,这种植物可 ...
- hdu 3836 Equivalent Sets(强连通分量--加边)
Equivalent Sets Time Limit: 12000/4000 MS (Java/Others) Memory Limit: 104857/104857 K (Java/Other ...
- php-fpm 如果dm设置为 static,那么其实只有pm.max_children这个参数生效。系统会开启设置数量的php-fpm进程。
php-fpm未优化网友反映的问题 1.最近将Wordpress迁移至阿里云.由于自己的服务器是云服务器,硬盘和内存都比较小,所以内存经常不够使,通过ps ax命令查看后,发现启动php-fpm进程数 ...
- 响应式网页设计:rem、em设置网页字体大小自适应
「rem」是指根元素(root element,html)的字体大小,好开心的是,从遥远的 IE6 到版本帝 Chrome 他们都约好了,根元素默认的 font-size 都是 16px.这样一个新的 ...
- C语言 百炼成钢26
/* 题目62: 有一下特征字符串"eerrrrqqAB33333ABa333333ABjsfdsfdsa" 编写一个业务函数, 实现功能1:实现按照子串"AB" ...
- 【BZOJ】1656:[Usaco2006 Jan]The Grove 树木(bfs+特殊的技巧)
http://www.lydsy.com/JudgeOnline/problem.php?id=1656 神bfs! 我们知道,我们要绕这个联通的树林一圈. 那么,我们想,怎么才能让我们的bfs绕一个 ...
- python urllib2导出elasticsearch数据时 返回 "urllib2.HTTPError: HTTP Error 500: Internal Server Error"
0.业务场景 将ES中某个index的某个字段的所有数据,导出到文件中 1.ES数据导出方法简述 ES数据导出方法,我主要找到了以下几个方面,欢迎大家补充: ES官方API:snapshot and ...