java操作properties文件(一)

2014-11-24 02:01:17 · 作者: · 浏览: 2

Java代码

package com.ccdevote.www.common.PropertiesDeal;

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

import java.util.Properties;

/**

* Properties 类存在于包Java.util 中,该类继承自Hashtable ,它提供了几个主要的方法:1.load

* (nputStream inStream) ,从输入流中读取属性列表(键和元素对)。2.getProperty(String key),

* 用指定的键在此属性列表中搜索属性。也就是通过参数key ,得到key 所对应的value 。3.setProperty ( String

* key, String value) ,调用Hashtable 的方法put 。他通过调用基类的put方法来设置 键- 值对。

* 通过对指定的文件(比如说上面的test.properties 文件)进行装载来获取该文件中的所有键- 值对。以供getProperty (

* String key)

*

* 来搜索。4.store(OutputStream out,String comments) ,以适合使用load 方法加载到Properties

* 表中的格式,将此Properties 表中的属性列

*

* 表(键和元素对)写入输出流。与load 方法相反,该方法将键- 值对写入到指定的文件中去。5.clear() ,清除所有装载的 键-

* 值对。该方法在基类中提供。 有了以上几个方法我们就可以对.properties 文件进行操作了! 总结:

* java的properties文件需要放到classpath下面,这样程序才能读取到, 有关classpath实际上就是java类或者库的存放路径:

* 在java工程中,properties放到class文件一块; 在web应用中,最简单的方法是放到web应用的WEB-INF\classes 目录下即可,

* 也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到classpath变量中,这样也也可以读取到

*

* 。 在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF\classes其实也是,

* java工程的

*

* class文件目录也是。

*/

public class PropertiesTools {

/*

* 读取properties的全部信息

*/

public static void readProperties(String fileNamePath) throws IOException {

Properties props = new Properties();

InputStream in = null;

try {

in = new BufferedInputStream(new FileInputStream(fileNamePath));

// 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中

// in = propertiesTools.class.getResourceAsStream(fileNamePath);

props.load(in);

Enumeration en = props.propertyNames();

while (en.hasMoreElements()) {

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

String Property = props.getProperty(key);

System.out.println(key + "=" + Property);

}

} catch (Exception e) {

if (null != in)

in.close();

e.printStackTrace();

} finally {

if (null != in)

in.close();

}

}

/*

* 根据key读取value

*/

public static String getValue(String fileNamePath, String key)

throws IOException {

Properties props = new Properties();

InputStream in = null;

try {

in = new FileInputStream(fileNamePath);

// 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中

// in = propertiesTools.class.getResourceAsStream(fileNamePath);

props.load(in);

String value = props.getProperty(key);

// 有乱码时要进行重新编码

// new String(props.getProperty("name").getBytes("ISO-8859-1"),

// "GBK");

return value;

} catch (IOException e) {

e.printStackTrace();

return null;

} finally {

if (null != in)

in.close();

}

}

/*

* 写入properties信息

*/

public static void setProperties