在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. ORACLE中关于 char 和 varchar2 的比较

    先建表做一个测试: ) , VARC2 )), CHAR2 ) ; INSERT INTO TT VALUES('A','A','A') ; INSERT INTO TT VALUES('A','A ...

  2. 加密web.config中的邮件配置mailSettings

    加密: 在命令提示符下键入: aspnet_regiis -pef connectionStrings 要加密的web.config完整路经 演示样例:C:\Program Files (x86)\M ...

  3. button按钮可点和不可点:

    button按钮可点和不可点: document.getElementById("check").disabled=true; document.getElementById(&q ...

  4. jQuery Colorbox使用教程

    jQuery Colorbox是一款弹出层,内容播放插件,效果极佳,最关键的是大小只有10KB,当然我主要是用来弹出图片啦,(之前介绍过jquery Fancybox插件,个人很喜欢).jQuery ...

  5. Linux基础命令(2)

      Fskey servername scp命令 grep 命令 find 命令 echo 命令 xargs 命令 file 命令 cat 命令 /dev/null tar 打包 gzip 压缩 示例 ...

  6. Dynamics CRM 系统自己定义部分的语言翻译

    Dynamics CRM 自带语言切换功能,在官网下载所需语言包安装后,在设置语言中就能看到你所加入的语言.勾选要启用的语言应用就可以.再打开系统设置--语言就能看到可更改用户界面语言的显示了. wa ...

  7. Spring工具类

    文件资源访问 1.统一资源访问接口 Resource 2.实现类 FileSystemResource 通过文件系统路径访问 ClassPathResource 通过classpath路径访问 Ser ...

  8. commit和rollback

    COMMIT过程·已经在 SGA(系统全局区域)中产生了回滚段(Rollback segment)记录.·已经在 SGA 中产生了修改数据块.·已经在 SGA 中产生了上面两条的缓冲重做(redo). ...

  9. mysql "ON DUPLICATE KEY UPDATE" 的使用

    ON DUPLICATE KEY UPDATE 语法并不是SQL的标准语法,如果在句尾指定该语法,它会根据指定的主键或者唯一标示索引来更新数据库的内容 具体的操作是想根据唯一标示查看数据库是否存在该记 ...

  10. Hadoop格式化HDFS报错java.net.UnknownHostException: centos64

    异常描述 在对HDFS格式化,执行hadoop namenode -format命令时,出现未知的主机名的问题,异常信息如下所示: [shirdrn@localhost bin]$ hadoop na ...