【Java编程】写入、读取、遍历Properties文件

时间:2022-09-18 16:36:58

在Java开发中通常我们会存储配置參数信息到属性文件。这种属性文件能够是拥有键值对的属性文件,也能够是XML文件。关于XML文件的操作,请參考博文【Java编程】DOM XML Parser 解析、遍历、创建XML

在该篇博文中,我将展示怎样向属性文件写入键值对。怎样读取属性文件里的键值对,怎样遍历属性文件。

1、向属性文件里写入键值对

【Java编程】写入、读取、遍历Properties文件

特别注意:

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();
}
}
}
}
}

运行单元測试后。属性文件内容例如以下:

【Java编程】写入、读取、遍历Properties文件

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYW5kaWVfZ3Vv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

2、读取属性文件里的键值对

【Java编程】写入、读取、遍历Properties文件

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例如以下:

【Java编程】写入、读取、遍历Properties文件

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文件来当做配置文件,方便用户对系统参数进行调整. 那么本片就来简单的介绍下,如何使用Prop ...

  2. SpringBoot读取application&period;properties文件

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

  3. Java读取修改Properties文件

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

  4. Java编程的逻辑 &lpar;64&rpar; - 常见文件类型处理&colon; 属性文件&sol;CSV&sol;EXCEL&sol;HTML&sol;压缩文件

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

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

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

  6. SpringBoot读取配置文件(从classpath&sol;file读取yml&sol;properties文件&rpar;

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

  7. java获取tomcat中的properties文件

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

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

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

  9. java读取本地properties文件

    package cn.edu.hbcf.pojo; import java.io.FileNotFoundException; import java.io.IOException; import j ...

随机推荐

  1. MongoDB安装与故障

    下载完毕后   bin为官方代码   data为自行创建的文件夹 db存在数据 log存在日志   启动MongoDB 通过cmd到db的文件目录 通过mongod.exe代码执行data下的log文 ...

  2. FTP的搭建与虚拟目录作用&lt&semi;之简单讲解&gt&semi;

    操作系统:win7 VS2010编写WebService与在IIS的发布<之简单讲解>中我已经说了IIS安装与使用,不明白的可以跳过去看. 1.添加FTP站点 2. 3. 4. 5. zq ...

  3. 【《zw版&&num;183&semi;Halcon与delphi系列原创教程》 zw&lowbar;halcon人脸识别

    [<zw版·Halcon与delphi系列原创教程>zw_halcon人脸识别 经常有用户问,halcon人脸识别方面的问题. 可能是cv在人脸识别.车牌识别方面的投入太多了. 其实,人脸 ...

  4. Lambda GroupBy Sum

    DataTable dt = new DataTable(); dt.AsEnumerable().GroupBy(r => r["ShopName"]) .Select(g ...

  5. 编写并发程序 Inversion

    做完了 scala parallel 课程作业后,觉得 scala 写并发程序的便捷性是 java 永远都追不上的.scala 的Future 和 Promise,java 里 Future 和 Co ...

  6. android开源项目---blog篇

    本文转载于:http://blog.csdn.net/likebamboo/article/details/19081241 主要介绍那些乐于分享并且有一些很不错的开源项目的个人和组织.Follow大 ...

  7. undrop for innodb c&lowbar;parser 源码分析

    一,主函数功能: 1,分析命令行参数,保存在全局变量中; 2,打开文件,加载表定义sql,调用分析函数开始处理; 3,打印导入数据的sql语句; 二,文件处理函数,void process_ibfil ...

  8. cogs&lowbar;14&lowbar;搭配飞行员&lowbar;&lpar;二分图匹配&plus;最大流&comma;网络流24题&num;01&rpar;

    描述 http://cojs.tk/cogs/problem/problem.php?pid=14 有一些正飞行员和副飞行员,给出每个正飞行员可以和哪些副飞行员一起飞.一架飞机上必须一正一副,求最多多 ...

  9. 基于itchat的微信群聊小助手基础开发(一)

    前段时间由于要管理微信群,基于itchat开发了一个简单的微信机器人 主要功能有: 图灵机器人功能 群聊昵称格式修改提示 消息防撤回功能 斗图功能 要开发一个基于itchat的最基本的聊天机器人,在g ...

  10. maven---settings&period;xml配置

    <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://mav ...