在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

Java - The Properties Class

6、你可能感兴趣的文章

【Java编程】DOM XML Parser解析、遍历、创建XML

【Java编程】SAX XML Parser解析、生成XML文件

【Java编程】写入、读取、遍历Properties文件的更多相关文章

  1. java如何读取和遍历properties文件

    在java项目开发过程中,使用properties文件作为配置基本上是必不可少的,很多如系统配置信息,文件上传配置信息等等都是以这种方式进行保存.同时学会操作properties文件也是java基础. ...

  2. Java程序员的日常—— Properties文件的读写

    在日常的Java程序开发中,Properties文件的读写是很常用的.经常有开发系统通过properties文件来当做配置文件,方便用户对系统参数进行调整. 那么本片就来简单的介绍下,如何使用Prop ...

  3. SpringBoot读取application.properties文件

    http://blog.csdn.net/cloume/article/details/52538626 Spring Boot中使用自定义的properties Spring Boot的applic ...

  4. Java读取修改Properties文件

    properties文件是我们经常需要操作一种文件,它使用一种键值对的形式来保存属性集. 无论在学习上还是工作上经常需要读取,修改,删除properties文件里面的属性. 本文通过操作一个prope ...

  5. Java编程的逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  6. ResourceBundle读取中文properties文件问题

    昨天遇到一个问题,用ResourceBundle读取中文字符串资源文件时,死活读不出来. 一开始以为是文件路径不对,后来发现如果默认properties文件时英文就没问题.我的项目代码是在src目录下 ...

  7. SpringBoot读取配置文件(从classpath/file读取yml/properties文件)

    一.读取properties文件 使用配置项@PropertySource   二.读取yml文件 启动类添加下面代码: @Bean public static PropertySourcesPlac ...

  8. java获取tomcat中的properties文件

    System.getProperty("catalina.home") 获取tomcat的绝对路径 获取文件的绝对路径 在windous中拼接路径是" \ " ...

  9. java通过CLASSPATH读取包内文件

    读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流:InputStream in = ReadFile.class.getResourceAsSt ...

随机推荐

  1. url中的查询字符串的参数解析

    <script> // 查询字符串函数location.search;"?q=javascript" function getQueryStringArgs(){ // ...

  2. [转]C/C++中volatile关键字详解

    http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777432.html

  3. Makefile 13——理解make的解析行为

    make是以从上到下的顺序读入Makefile中的内容的.然而,处理Makefile中的语句却并非完全从上到下. 大体上,make处理一个Makefile分为两个阶段.第一个阶段包含: 1.make读 ...

  4. JAVA中使用P和Q分量计算N和D进行RSA运算

    最近在使用Java中需要使用PQ形式的私钥进行RSA加解密运算,本来以为Java中应该很多类似的例子,发现所有的例子都是从ND形式的私钥,竟然没有人用分量P和Q计算N和D进行运算.对Java使用RSA ...

  5. CSS学习笔记(3)--表格边框

    http://www.alixixi.com/web/a/2009082657736.shtml 对于很多初学HTML的人来说,表格<table>是最常用的标签了,但对于表格边框的控制,很 ...

  6. 今天升级netbean出错

    出现:无法初始化 UI netbean 由于ubuntun装的是open jdk 直接删除open jdk就可以 sudo apt-get autoremove open-jdk*

  7. Lua一般都用来干什么,有什么优点

    Lua一般用于嵌入式应用,现在越来越多应用于游戏当中,魔兽世界,愤怒的小鸟都有用到. Lua极易嵌入到其他程序,可当做一种配置语言. 还有很多需要性能的地方,比如:游戏脚本,nginx,wiresha ...

  8. Web安全测试(一)-手工安全测试方法&修改建议

    常见问题 1.XSS(CrossSite Script)跨站脚本攻击 XSS(CrossSite Script)跨站脚本攻击.它指的是恶意攻击者往Web 页面里插入恶意 html代码,当用户浏览该页之 ...

  9. Oracle安装完成后,如何用命令行启动和关闭数据库?

    Oracle安装完成后,如何用命令行启动和关闭数据库? 解答: 打开:STARTUP [FORCE] [RESTRICT] [PFILE= filename] [OPEN [RECOVER][ dat ...

  10. Java语言中两种异常的差别

    Java提供了两类主要的异常:runtime exception和checked exception.所有的checked exception是从java.lang.Exception类衍生出来的,而 ...