您的位置:首页 > 编程语言 > Java开发

Java读写properties配置文件

2014-12-09 17:16 716 查看
Java读写配置文件注意以下几点:

1. 配置文件config.properties在src目录下,编译后会在classes目录下

2. 通常写入不了一般都是路径错误,写到其他目录去了。

3.JDK Properties 类读取的文件是不允许有非 ASCII 码字符的,文件需要使用 JDK 的 native2ascii 工具转换一下

package com.util;

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;

/**
* 功能:读写配置文件
* @author Adam
*
*/
public class PropertyHelper {
static String profilepath = PropertyHelper.class.getClassLoader().
getResource("").getPath() + "config.properties";
private static Properties props = new Properties();
static {
try {
System.out.println("配置文件路径:"+profilepath);
InputStream is = new BufferedInputStream (new FileInputStream(profilepath));
props.load(is);
is.close();
}catch (IOException e) {
e.printStackTrace();
}
}

/**
* 功能:根据key获得value
* @param key:key
* @return String:value
*/
public static String getValueByKey(String key) {
return props.getProperty(key);
}

/**
* 功能:根据属性文件路径和key读取value
* @param filePath:属性文件路径
* @param key:键名
*/
public static String readValue(String filePath, String key) {
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
return props.getProperty(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 功能:写入properties文件的键值对,key存在,则修改,key不存在则添加
* @param keyname:key
* @param keyvalue:value
*/
public static void writeProperties(String keyname,String keyvalue) {
try {
props.load(new FileInputStream(profilepath));
OutputStream fos = new FileOutputStream(profilepath);
props.setProperty(keyname, keyvalue);
props.store(fos, "Update '" + keyname + "' value");
} catch (IOException e) {
System.err.println("属性文件写入异常");
}
}

/**
* 功能:读取properties的全部信息
* @param filePath:属性文件路径
*/
public static void readProperties(String filePath) {
Properties props = new Properties();
try {
InputStream is = new BufferedInputStream (new FileInputStream(filePath));
props.load(is);
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) {
e.printStackTrace();
}
}

public static void main(String[] args) {
System.out.println(PropertyHelper.getValueByKey("SYSTEM_SMTP"));
PropertyHelper.writeProperties("SYSTEM_SMTP","中文");
readProperties(profilepath);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: