Properties的构造函数有两个,一个不带参数,一个使用一个Properties对象作为参数。
使用Properties读取.properties文件
test.properties文件如下:
#测试环境配置:平台路径配置
jstrd_home=D:/TMS2006/webapp/tms2006/WEB-INF/
dbPort = localhost
databaseName = mydb
dbUserName = root
dbPassword = root
# 以下为数据库表信息
dbTable = mytable
# 以下为服务器信息
ip = 192.168.0.9
读取test.properties的方法如下:
impor java.io.*;
import java.util.*;
public class ReadProperties
{
public static void main(String[] args) {
File pFile = new File("e:\\test.properties"); // properties文件放在e盘下(windows)
FileInputStream pInStream=null;
try {
pInStream = new FileInputStream(pFile );
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Properties p = new Properties();
try {
p .load(pInStream ); //Properties 对象已生成,包括文件中的数据
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Enumeration enu = p.propertyNames(); //取出所有的key
//输出--1
p.list(System.out) ; //System.out可以改为其他的输出流(包括可以输出到文件)
//输出--2
while( enu .hasMoreElements())
{
System.out.print("key="+enu.nextElement());
System.out.print("value="+p.getProperty((String)enu .nextElement()));
}
}
}
读取xml格式的配置文件
test.xml文件ruxi
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="koo">bar</entry>
<entry key="fu">baz</entry>
</properties>
读取xml的方法
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
File pFile = new File("e:\\test.xml"); // properties文件放在e盘下(windows)
FileInputStream pInStream = null;
try {
pInStream = new FileInputStream(pFile);
Properties p = new Properties();
p.loadFromXML(pInStream);
p.list(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过list 方法将Properties写入Properties文件
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id","dean");
p.setProperty("password","123456");
try{
PrintStream fW = new PrintStream(new File("e:\\test1.properties"));
p.list(fW ); } catch (IOException e) {
e.printStackTrace();
}
}
}
保存为xml
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id","dean");
p.setProperty("password","123456");
try{
PrintStream fW = new PrintStream(new File("e:\\test1.xml"));
p.storeToXML(fW,"test");
} catch (IOException e) {
e.printStackTrace();
}
}
}