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

执行单元测试后,属性文件内容如下:

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

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文件

时间: 2024-08-23 23:57:31

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

fmt 国际化格式标签库(读取application.properties文件)

国际化格式标签库包括国际化,消息和数字日期格式化: (1) 国际化:<fmt:setLocale> <fmt::requestEncoding> 如: <%@ page language="java" contentType="text/html; charset=gb2312" import="java.util.*"%> <%@ taglib prefix="c" uri=&quo

SpringBoot读取application.properties文件

SpringBoot读取application.properties文件,通常有3种方式 1. @Value  例如: @Value("${spring.profiles.active}") private String profileActive;------相当于把properties文件中的spring.profiles.active注入到变量profileActive中 2. @ConfigurationProperties  例如: @Component@Configurat

springboot中读取自定义properties文件

一.在高版本的springboot中,@ConfigurationProperties(prefix = "wisely2",locations = "classpath:wisely.properties")这个注解不支持了,所以我们要另辟蹊径 二.使用组合式注解: 1.自定义config.properties文件: 1 config.fileServer=/root/jzyp/staticserver/webapps/ROOT/server 2 config.s

编程技巧 - 读取完整的文件(C++)

读取完整的文件(C++) 本文地址: http://blog.csdn.net/caroline_wendy C++: 把文本文件(txt)的所有内容读入字符串(string), 最高效的方法. 代码: /* * main.cpp * * Created on: 2014年6月17日 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <fstream> #include <st

java util工具读取国际化资源文件

Locale ResourceBundle Locale读取资源文件 package yycg.util; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.ResourceBundle;

spring boot 读取自定义properties文件

@Configuration@Componentpublic class PropertiesConfig { private static final String[] properties = {"/application.properties"}; private static Properties props; private static Map<Object, Object> propertiesMap = new HashMap(); public Prope

java使用poi读取excel(.xlsx)文件

经过一番搜索发现,java操纵excel文件常用的有jxl和poi两种方式,孰好孰坏看自己需求而定. 其中最主要的区别在于jxl不支持.xlsx,而poi支持.xlsx 这里介绍的使用poi方式(XSSFWorkbook),实际上poi提供了HSSFWorkbook和XSSFWorkbook两个实现类.区别在于HSSFWorkbook是针对.xls文件,XSSFWorkbook是针对.xslx文件. 首先明确一下基本概念: 先创建一个工作簿,一个工作簿可以有多个工作表,一个工作表可以有多个行,一

Asp.Net写入读取Xml(处理文件权限)

1,网上关于读取写入Xml的博客比较多,参考了发现提到Xml文件权限的博客比较少.因为在开发中我发现,如果文件存于一些没有权限的路径,代码是访问不到该文件,页面会报错提示403,Forbidden.意思是禁止,也就是没有权限.需要用代码给文件EveryOne赋予完全控制权限.希望我的博客能帮助一些在权限方面遇到问题的朋友. 2,判断文件文件夹和文件是否存在(写入时会自动创建Xml,但是如果没有权限,会创建失败,所以我觉得先用FileStream把文件创建出来比较保险); public strin

[转]World Wind Java开发之五——读取本地shp文件

World Wind Java 使用IconLayer图层类表现点和多点数据,使用RenderableLayer图层表现线和面数据,一个图层只能对应一组shape文件.World Wind Java首先使用ShapefileLoader类完成对shape文件的读取和加载,再通过createLayerFromSource方法创建RenderableLayer,最后将创建的Layer加在layers上.源码如下: /** * * 方法名称: AddShapeData : * 方法描述: 添加本地sh