【0】README
0.1)以下全文转自 : http://trans.blog.51cto.com/503170/110227/
【1】认识properties文件
- 1、 properties文件是一个文本文件
- 2、 properties文件的语法有两种,一种是注释,一种属性配置。
- 注 释:前面加上#号
- 属性配置:以“键=值”的方式书写一个属性的配置信息。
- 3、 properties文件的一个属性配置信息值可以换行,但键不可以换行。值换行用“\”表示。
- 4、 properties的属性配置键值前后的空格在解析时候会被忽略。
- 5、 properties文件可以只有键而没有值。也可以仅有键和等号而没有值,但无论如何一个属性配置不能没有键。
【2】java.util.Properties 类
2.1)properties文件与Properties类的关系
- 通过properties文件可以填充Properties类。
- 也可以通过xml文件来填充Properties类。
- 可以通过绝对路径方式加载Properties文件信息,也可以使用相对路径加载。
2.2)看个荔枝:
- 2.2.1)以绝对相对路径方式加载properties文件信息。
- 2.2.2)将Properties对象持久化到一个properties文件或者一个xml文件中。
- 2.2.3)修改并持久化properties文件。
- 2.2.4) for full source code , please visit https://github.com/pacosonTang/core-java-volume/blob/master/chapter13/PropertiesTest.java
package com.corejava.chapter13;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import static java.lang.System.*;
public class PropertiesTest
{
public static void main(String[] args) throws IOException
{
test();
}
public static void test() throws IOException
{
InputStream is = new FileInputStream("D://Users//corejava//corein.properties");
Properties prop = new Properties();
prop.load(is);
for (Object key : prop.keySet())
out.print(key + " ");
OutputStream os1 = new FileOutputStream("D://Users//corejava//coreout.xml");
OutputStream os2 = new FileOutputStream("D://Users//corejava//coreout.properties");
prop.storeToXML(os1, "output to .XML");
prop.store(os2, "output to .properties");
is.close();
os1.close();
os2.close();
// load info from xml
prop.loadFromXML(new FileInputStream("D://Users//corejava//coreout.xml"));
out.println();
for (Object key : prop.keySet())
out.print(key + " ");
prop.put("aaa", "110");
prop.storeToXML(new FileOutputStream("D://Users//corejava//coreout.xml"), "update info");
}
}
2.3) input and output files: