Properties类的用法

在java.util包下面有一个类Properties,该类主要用于读取以项目的配置文件(以.properties结尾的文件和xml文件)。

一. Properties结构

类继承结构如下:

class Properties extends Hashtable<Object,Object>

从上面可以看出来Properties继承自Hashtable。

二. 具体案例

案例一: 读取.properties文件。

首先建立一个.properties文件,内容如下:

#网站信息
website = http://www.swiftlet.net
author = admin
date = 2015年

java类如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
 
public class ReadProperties
{
    public static void main(String[] args)
    {
        File file = new File("c:\\test.properties");
        FileInputStream in = null;
        try
        {
            in = new FileInputStream(file);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        Properties p = new Properties();
        try
        {
            p.load(in);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        p.list(System.out);
    }
}

输出结果如下:

案例二: 读取.xml文件。

首先建立一个.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="website">swiftlet.net</entry>
<entry key="author">admin</entry>
</properties>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
 
public class ReadXml
{
    public static void main(String[] args)
    {
 
        File file = new File("c:\\test.xml");
        FileInputStream in = null;
        try
        {
            in = new FileInputStream(file);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        Properties p = new Properties();
        try
        {
            p.loadFromXML(in);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        p.list(System.out);
    }
}

输出结果如下:

三. 常见问题:

Invalid byte 1 of 1-byte UTF-8 sequence. 产生这个异常的原因是:
所读的xml文件实际是GBK或者其他编码的,而xml内容中却用<?xml version="1.0" encoding="utf-8"?>指定编码为utf-8,所以就报异常了!常见的解决访问有两种:
第一:可以直接在XML文件中更改UTF-8为GBK或GB2312
         <?xml   version="1.0"   encoding="GB2312"?>
第二:将xml文件的编码格式修改为utf-8重新保存一下就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值