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

java操作properties文件

2013-06-18 21:12 274 查看
package comm.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

/**
* 该类为java操作.properties文件的工具类
*
* @author wxq
*
*/
public class PropertyFileUtil {
String propertyFileName = "test.properties";
// 读取的文件是否为XML文件
boolean isXMLFile = false;
Properties prop = null;

/**
* 获取property文件
*
* @return
* @throws URISyntaxException
*/
private File getPropertyFile() throws URISyntaxException {
File propFile = null;
URL url = ClassLoader.getSystemResource(propertyFileName);
propFile = new File(url.toURI());
return propFile;
}

/**
* 将properties文件中的信息读到Properties对象中
*
* @throws IOException
*/
private void readPropertiesFromPropFile() throws IOException {
InputStream in = null;
in = PropertyFileUtil.class.getResourceAsStream("/" + propertyFileName);
// in=PropertyFileUtil.class.getClassLoader().getSystemResourceAsStream("test.properties");
prop = new Properties();
if (isXMLFile) {
prop.loadFromXML(in);
} else {
prop.load(in);
}
in.close();
}

/**
* 读取指定key的value值
*
* @param key
* @return
* @throws IOException
*/
public String getValueOfPropertyFile(String key) throws IOException {
this.readPropertiesFromPropFile();
return prop.getProperty(key);
}

/**
* 向properties文件中增加key&value
*
* @param key
* @param value
* @return
* @throws Exception
*/
public boolean addOrUpdatePropertyIntoPropFile(String key, String value)
throws Exception {
boolean isAddSuccess = false;
File propFile = null;
FileOutputStream fos = null;
if (key != null && !key.equals("")) {
propFile = getPropertyFile();
this.readPropertiesFromPropFile();
prop.setProperty(key, value);
fos = new FileOutputStream(propFile);
prop.store(fos, "add " + key + " " + value);
fos.flush();
fos.close();
isAddSuccess = true;
}
return isAddSuccess;
}

/**
* 从properties文件中删除一行
*
* @param key
* @return
* @throws URISyntaxException
* @throws IOException
*/
public boolean delPropertyFromPropFile(String key)
throws URISyntaxException, IOException {
boolean isAddSuccess = false;
File propFile = null;
FileOutputStream fos = null;
if (key != null && !key.equals("")) {
propFile = getPropertyFile();
this.readPropertiesFromPropFile();
prop.remove(key);
fos = new FileOutputStream(propFile);
prop.store(fos, "delete " + key);
fos.flush();
fos.close();
isAddSuccess = true;
}
return isAddSuccess;
}

/*
* XML文件示例 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties
* SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties>
* <comment></comment> <entry key="a">1</entry> </properties>
*/

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  property java