java中properties作用,Java中Properties的使用详解

Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支 持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。今天,我们就开始Properties的使用。

Java中Properties的使用

Properties的文档说明:

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

Properties类的描述:

public class Properties extends Hashtable

测试的项目结构如下:

5f1e62a8f0fab9079deefec8a53e534c.png

一、在huhx.properties文件中,我们为也方便,加入一条数据:

name=huhx

二、将huhx.properties文件加载读取,得到相应的属性

Properties properties = new Properties();

FileInputStream fis = new FileInputStream("huhx.properties");

properties.load(fis);

System.out.println(properties.get("name"));

三、Properties的list方法的使用

PrintStream printStream = System.out;

properties.list(printStream);

list方法的具体代码:

public void list(PrintStream out) {

out.println("-- listing properties --");

Hashtable h = new Hashtable();

enumerate(h);

for (Enumeration e = h.keys() ; e.hasMoreElements() ;) {

String key = (String)e.nextElement();

String val = (String)h.get(key);

if (val.length() > 40) {

val = val.substring(0, 37) + "...";

}

out.println(key + "=" + val);

}

}

四、Properties的store方法的使用

OutputStream outputStream = new FileOutputStream("huhx.txt");

properties.store(outputStream, "comments");

五、Properties的storeToXML方法的使用

OutputStream outputStream2 = new FileOutputStream("huhx.xml");

properties.storeToXML(outputStream2, "comments");

六、最终生成的文件如下:

huhx.txt:

#comments

#Thu May 19 19:19:36 CST 2016

name=huhx

huhx.xml:

comments

huhx

友情链接,PropertiesTest.java:

package com.huhx.linux;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.io.PrintStream;

import java.util.Properties;

public class PropertiesTest {

public static void main(String[] args) throws Exception {

// 一般Properties的使用

Properties properties = new Properties();

FileInputStream fis = new FileInputStream("huhx.properties");

properties.load(fis);

System.out.println(properties.get("name"));

// 以下是测试的部分

PrintStream printStream = System.out;

properties.list(printStream);

OutputStream outputStream = new FileOutputStream("huhx.txt");

properties.store(outputStream, "comments");

OutputStream outputStream2 = new FileOutputStream("huhx.xml");

properties.storeToXML(outputStream2, "comments");

}

}

以上所述是小编给大家介绍的Java中Properties的使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值