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重新保存一下就可以了。

你可能感兴趣的:(properties)