在JDK5中,properties文件的格式可以由XML构成,这里给出了一个读取/书写XML格式properties文件的例子。
因为使用了XML,所以文件内容支持了CJKV(中文、日文、韩文、越南语)。可以直接书写、调用。
例子代码:
输出结果:
因为使用了XML,所以文件内容支持了CJKV(中文、日文、韩文、越南语)。可以直接书写、调用。
例子代码:
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Properties;
- /**
- *
- *
- * @author 郝春利
- * @since 2008/09/11
- * @version $Revision:$
- */
- public class PropertiesTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // 书写properties文件
- Properties properties = new Properties();
- properties.put("ONE", "1");
- properties.put("TWO", "2");
- properties.put("中文", "看看中文怎么样");
- properties.put("日本語", "日本語はどう?");
- properties.put("한국어", "한국어");
- properties.put("Thảo luận tiếng Việt", "Thảo luận tiếng Việt");
- OutputStream stream = null;
- http://www.loveapple.cn
- try {
- stream = new FileOutputStream("temp.xml");
- properties.storeToXML(stream, "Temporary Properties");
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }finally{
- try{
- stream.close();
- }catch(Exception e){
- }
- }
- // 读取properties文件
- Properties properties2 = new Properties();
- InputStream is = null ;
- try{
- is = new FileInputStream("temp.xml");
- properties2.loadFromXML(is);
- System.out.println(properties2);
- }catch (IOException e) {
- e.printStackTrace();
- }finally{
- try{
- is.close();
- }catch (Exception e) {
- }
- }
- }
- }
输出结果:
- <?xml version="1.0" encoding="UTF-8" standalone="no"?>
- <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
- <properties>
- <comment>Temporary Properties</comment>
- <entry key="TWO">2</entry>
- <entry key="ONE">1</entry>
- <entry key="한국어">한국어</entry>
- <entry key="Thảo luận tiếng Việt">Thảo luận tiếng Việt</entry>
- <entry key="日本語">日本語はどう?</entry>
- <entry key="中文">看看中文怎么样</entry>
- </properties>

该博客演示了如何使用Java读写XML格式的properties文件。首先创建Properties对象并添加键值对,然后通过OutputStream将数据保存到XML文件。接着,从XML文件中加载Properties对象并打印内容,支持多种语言字符的存储和读取。
7125

被折叠的 条评论
为什么被折叠?



