栏目:Java8基础 作者:admin 日期:2015-06-03 评论:1 点击: 4,298 次
在java.util包下面有一个类Properties,该类主要用于读取以项目的配置文件(以.properties结尾的文件和xml文件),本文给大家讲解一下Properties的用法。虽然网上也有不少关于Properties类的内容,但是文章的质量令人抓狂,所以金丝燕网重新整理了一遍。
class Properties extends Hashtable<Object,Object>
从上面可以看出来Properties继承自Hashtable。
首先建立一个.properties文件,内容如下:
1 2 3 4 |
#网站信息 website = http://www.swiftlet.net author = admin date = 2015年 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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文件,内容如下:
1 2 3 4 5 6 |
<?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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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重新保存一下就可以了。
------====== 本站公告 ======------
金丝燕网,一个严谨的网站!