博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java属性文件– java.util.Properties
阅读量:2532 次
发布时间:2019-05-11

本文共 8501 字,大约阅读时间需要 28 分钟。

Java properties file are used to store key-value pair configuration. java.util.Properties class is used to work with properties file in java.

Java属性文件用于存储键值对配置。 java.util.Properties类用于在Java中使用属性文件。

Java属性文件– java.util.Properties (Java Properties File – java.util.Properties)

In java properties file can be a normal property file with key-value pairs or it can be an XML file also.

在java中,属性文件可以是具有键值对的普通属性文件,也可以是XML文件。

In this java properties file example, we will show you how to write a property file in both formats and then read properties from both the configuration files.

在此Java属性文件示例中,我们将向您展示如何以两种格式写入属性文件,然后从两个配置文件中读取属性。

We will also show you how to load a properties file from the classpath and how to read all the keys from the properties file.

我们还将向您展示如何从类路径加载属性文件以及如何从属性文件读取所有键。

Java属性文件示例 (Java Properties File Example)

package com.journaldev.util;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.util.Set;public class PropertyFilesUtil {	public static void main(String[] args) throws IOException {		String propertyFileName = "DB.properties";		String xmlFileName = "DB.xml";		writePropertyFile(propertyFileName, xmlFileName);		readPropertyFile(propertyFileName, xmlFileName);		readAllKeys(propertyFileName, xmlFileName);		readPropertyFileFromClasspath(propertyFileName);	}	/**	 * read property file from classpath	 * @param propertyFileName	 * @throws IOException	 */	private static void readPropertyFileFromClasspath(String propertyFileName) throws IOException {		Properties prop = new Properties();		prop.load(PropertyFilesUtil.class.getClassLoader().getResourceAsStream(propertyFileName));		System.out.println(propertyFileName +" loaded from Classpath::db.host = "+prop.getProperty("db.host"));		System.out.println(propertyFileName +" loaded from Classpath::db.user = "+prop.getProperty("db.user"));		System.out.println(propertyFileName +" loaded from Classpath::db.pwd = "+prop.getProperty("db.pwd"));		System.out.println(propertyFileName +" loaded from Classpath::XYZ = "+prop.getProperty("XYZ"));			}	/**	 * read all the keys from the given property files	 * @param propertyFileName	 * @param xmlFileName	 * @throws IOException 	 */	private static void readAllKeys(String propertyFileName, String xmlFileName) throws IOException {		System.out.println("Start of readAllKeys");		Properties prop = new Properties();		FileReader reader = new FileReader(propertyFileName);		prop.load(reader);		Set keys= prop.keySet();		for(Object obj : keys){			System.out.println(propertyFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));		}		//loading xml file now, first clear existing properties		prop.clear();		InputStream is = new FileInputStream(xmlFileName);		prop.loadFromXML(is);		keys= prop.keySet();		for(Object obj : keys){			System.out.println(xmlFileName + ":: Key="+obj.toString()+"::value="+prop.getProperty(obj.toString()));		}		//Now free all the resources		is.close();		reader.close();		System.out.println("End of readAllKeys");	}	/**	 * This method reads property files from file system	 * @param propertyFileName	 * @param xmlFileName	 * @throws IOException 	 * @throws FileNotFoundException 	 */	private static void readPropertyFile(String propertyFileName, String xmlFileName) throws FileNotFoundException, IOException {		System.out.println("Start of readPropertyFile");		Properties prop = new Properties();		FileReader reader = new FileReader(propertyFileName);		prop.load(reader);		System.out.println(propertyFileName +"::db.host = "+prop.getProperty("db.host"));		System.out.println(propertyFileName +"::db.user = "+prop.getProperty("db.user"));		System.out.println(propertyFileName +"::db.pwd = "+prop.getProperty("db.pwd"));		System.out.println(propertyFileName +"::XYZ = "+prop.getProperty("XYZ"));		//loading xml file now, first clear existing properties		prop.clear();		InputStream is = new FileInputStream(xmlFileName);		prop.loadFromXML(is);		System.out.println(xmlFileName +"::db.host = "+prop.getProperty("db.host"));		System.out.println(xmlFileName +"::db.user = "+prop.getProperty("db.user"));		System.out.println(xmlFileName +"::db.pwd = "+prop.getProperty("db.pwd"));		System.out.println(xmlFileName +"::XYZ = "+prop.getProperty("XYZ"));		//Now free all the resources		is.close();		reader.close();		System.out.println("End of readPropertyFile");	}		/**	 * This method writes Property files into file system in property file	 * and xml format	 * @param fileName	 * @throws IOException	 */	private static void writePropertyFile(String propertyFileName, String xmlFileName) throws IOException {		System.out.println("Start of writePropertyFile");		Properties prop = new Properties();		prop.setProperty("db.host", "localhost");		prop.setProperty("db.user", "user");		prop.setProperty("db.pwd", "password");		prop.store(new FileWriter(propertyFileName), "DB Config file");		System.out.println(propertyFileName + " written successfully");		prop.storeToXML(new FileOutputStream(xmlFileName), "DB Config XML file");		System.out.println(xmlFileName + " written successfully");		System.out.println("End of writePropertyFile");	}}

When we run above java properties file example program, writePropertyFile method will write property files in both the format and it will be stored in the project root directory.

当我们在上述Java属性文件示例程序上运行时, writePropertyFile方法将以两种格式写入属性文件,并将其存储在项目根目录中。

Here are the property files created from writePropertyFile method.

这是从writePropertyFile方法创建的属性文件。

DB.properties

DB.properties

#DB Config file#Fri Nov 16 11:16:37 PST 2012db.user=userdb.host=localhostdb.pwd=password

DB.xml

DB.xml

DB Config XML file
user
localhost
password

Notice the comments in the property file, it gets generated because we passed the comment also while writing the files. If we pass comment as null, there will be no comments in the property files.

注意属性文件中的注释,它是生成的,因为我们在编写文件时也通过了注释。 如果我们将注释传递为null,则属性文件中将没有注释。

Here is the output of the above java properties file program:

这是上述java属性文件程序的输出:

Start of writePropertyFileDB.properties written successfullyDB.xml written successfullyEnd of writePropertyFileStart of readPropertyFileDB.properties::db.host = localhostDB.properties::db.user = userDB.properties::db.pwd = passwordDB.properties::XYZ = nullDB.xml::db.host = localhostDB.xml::db.user = userDB.xml::db.pwd = passwordDB.xml::XYZ = nullEnd of readPropertyFileStart of readAllKeysDB.properties:: Key=db.user::value=userDB.properties:: Key=db.host::value=localhostDB.properties:: Key=db.pwd::value=passwordDB.xml:: Key=db.user::value=userDB.xml:: Key=db.host::value=localhostDB.xml:: Key=db.pwd::value=passwordEnd of readAllKeysException in thread "main" java.lang.NullPointerException	at java.util.Properties$LineReader.readLine(Properties.java:434)	at java.util.Properties.load0(Properties.java:353)	at java.util.Properties.load(Properties.java:341)	at com.journaldev.util.PropertyFilesUtil.readPropertyFileFromClasspath(PropertyFilesUtil.java:31)	at com.journaldev.util.PropertyFilesUtil.main(PropertyFilesUtil.java:21)

So when we just give the file name, it looks for the file in project root directory, the same place where it stores the property files. But when we try to load a property file from the classpath, it throws because it tries to load the file from Classpath that is src directory of the project.

因此,当我们仅提供文件名时,它将在项目根目录中查找该文件,该目录与存储属性文件的位置相同。 但是,当我们尝试从类路径加载属性文件时,它会抛出因为它试图从类路径(即项目的src目录)加载文件。

So if we copy the properties file in the classes src directory, it’s able to load them and works fine.

In that case output of the readPropertyFileFromClasspath method is:

因此,如果我们将属性文件复制到classes src目录中,则可以加载它们并正常工作。

在这种情况下, readPropertyFileFromClasspath方法的输出为:

DB.properties loaded from Classpath::db.host = localhostDB.properties loaded from Classpath::db.user = userDB.properties loaded from Classpath::db.pwd = passwordDB.properties loaded from Classpath::XYZ = null

Also, notice that when we use the same Properties object to load another property file, we should clear its contents using clear() method. If we pass any key for which there is no value stored in the properties object, it returns null.

另外,请注意,当我们使用相同的Properties对象加载另一个属性文件时,应使用clear()方法清除其内容。 如果我们传递任何没有在属性对象中存储任何值的键,则它返回null。

That’s all for properties file in java.

这就是java中的属性文件。

翻译自:

转载地址:http://nuqzd.baihongyu.com/

你可能感兴趣的文章
实验二
查看>>
shell——按指定列排序
查看>>
crash 收集
查看>>
507 LOJ 「LibreOJ NOI Round #1」接竹竿
查看>>
UI基础--烟花动画
查看>>
2018. 2.4 Java中集合嵌套集合的练习
查看>>
精通ASP.NET Web程序测试
查看>>
vue 根据不同属性 设置背景
查看>>
51Nod1601 完全图的最小生成树计数 Trie Prufer编码
查看>>
Codeforces 1110D. Jongmah 动态规划
查看>>
android驱动在win10系统上安装的心酸历程
查看>>
优雅的程序员
查看>>
oracle之三 自动任务调度
查看>>
Android dex分包方案
查看>>
ThreadLocal为什么要用WeakReference
查看>>
删除本地文件
查看>>
FOC实现概述
查看>>
base64编码的图片字节流存入html页面中的显示
查看>>
这个大学时代的博客不在维护了,请移步到我的新博客
查看>>
GUI学习之二十一——QSlider、QScroll、QDial学习总结
查看>>