- 论坛徽章:
- 0
|
在软件开发过程中,有时需要把程序中的一些可变信息提取到一个可配置的文件中,以提高软件的灵活性。(这样作是很有好处的,嘿嘿, ~~~~~ 用户通过修改配置文件,避免了直接与代码接触,而又能适应自己的血球 ~~~~~ )
㊣ 重点类 java.util.Properties
http://java.sun.com/j2se/1.5.0/docs/api
㊣ ConfExecutor.java
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.Properties;
public class ConfExecutor {
private static String PROPERTIES_FILE_PATH = "conf.properties";
private static String XML_FILE_PATH = "conf.xml";
public static void main(String[] args) {
/**
* properties 文件
*/
Properties properties = new Properties();
// read conf.properties
try {
InputStream is = new FileInputStream(PROPERTIES_FILE_PATH);
properties.load(is);
properties.list(System.out);
is.close();
} catch (IOException pe) {
pe.printStackTrace();
}
// write conf.properties
try {
properties.setProperty("date", new Date().toString());
OutputStream os = new FileOutputStream(PROPERTIES_FILE_PATH);
properties.store(os, null);
os.close();
} catch (IOException pee) {
pee.printStackTrace();
}
/**
* xml 文件
*/
Properties xml = new Properties();
// read conf.xml
try {
InputStream is = new FileInputStream(XML_FILE_PATH);
xml.loadFromXML(is);
xml.list(System.out);
is.close();
} catch (IOException xe) {
xe.printStackTrace();
}
// write conf.xml
try {
xml.setProperty("date", new Date().toString());
OutputStream os = new FileOutputStream(XML_FILE_PATH);
xml.storeToXML(os, null);
os.close();
} catch (IOException xee) {
xee.printStackTrace();
}
}
}
㊣ conf.properties
#Tue Aug 29 15:24:04 CST 2006
date=Tue Aug 29 15\:24\:04 CST 2006
author=bbflyerwww
homepage=http\://bbflyerwww.cublog.cn/
㊣ conf.xml
Tue Aug 29 15:24:04 CST 2006
bbflyerwww
http://bbflyerwww.cublog.cn/
㊣ properties.dtd
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/22660/showart_162022.html |
|