java中通常使用Properties读取配置文件,一般以.properties结尾的文件都是配置文件,用以存放一些配置参数,比如url,数据库的名称密码等,java代码都是通过Properties类进行文件的读取和操作,因为 Properties采用键值对的方式,属性文件也是以键值对应的,Properties可以通过集合的方式读取配置文件
首先是java文件读取.properties文件,可以采用class变量的getResource方式
实例:String path = PropUtils.class.getResource("/ly.properties").getPath();
它提供如下几个方法
1 getProperty(Stirig key)方法:此方法主要是用指定的键在此属性列表中搜索属性。
2 load(inputStream in)此方法用来读取输入流中的属性列表,通过指定的文件来装载获取该文件中的键值对,以供getProperties()来搜索
3 setProperties(String key,String value)该方法调用自hashTable的put方法,用于向文件中新增和修改键值属性,如果该键值存在,则修改该主键的值,如果主键不存在,则新增该键值
4store ( OutputStream out, String comments)此方法按照load方法加载到Properties文件中的格式,将properties文件属性写入输出流,该方法将键值对写入到指定的文件当中
5clear()清除所有装载的 键 - 值对。该方法在基类中提供。
package com.lvluo.interf.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
* 读取配置文件的属性。
*
* @author yan
*/
public class PropUtils {
public static final Properties properties = new Properties();
static {
try {
//Properties prop = new Properties();
//读取文件路径
String path = PropUtils.class.getResource("/ly.properties").getPath();
//java解决空格乱码问题
path= java.net.URLDecoder.decode(path, "utf-8");
//对文件进行读取,就是字节流的输入
InputStream in = new FileInputStream(path);
//从输入流中读取相应的属性,通过对指定文件进行装载来读取文件中的键值对
properties.load(in);
//调用hashTable的方法put来设置键值对
properties.setProperty("validTime1", "15");
//将文件进行输出
OutputStream out=new FileOutputStream(path);
//将此表中的属性列表写入到输出流中
properties.store(out, "aa");
//关闭此输入流并释放与该流相关的所有资源
in.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
//通过指定的参数key,获取相对应的value值
String value = properties.getProperty(key);
return value;
}
public static void main(String[] args) {
System.out.println(Integer.valueOf(PropUtils.getProperty("validTime").trim()));
System.out.println(Integer.valueOf(PropUtils.getProperty("validTime1").trim()));
System.out.println(PropUtils.getProperty("callback_key").trim());
}
}