经常用到,Java对Properties文件操作,在这里做一个小结。
Java对Properties文件的操作可以说是“不尽人意”,这里时间关系大体先说一下,回头慢慢说。
1.java读Properties文件,经常能读出一些乱码。
2.java写Properties文件,用能把以前的Properties文件的注释弄丢了。
上面的[b]public String getPropertyValue(String key)[/b]是不存在什么问题的,因为毕竟就是一个读取操作,但是[b]public void setPropertyValue(String key, String value)[/b]会出现很严重的问题,因为它会把你文件中所有的注释都忽略掉,你保存文件后发现所有的注释都没有了,解决这个问题我找了好多资料,没有什么好办法。最好利用了一个笨办法,就是写入操作不用Properties类机型操作,而是直接利用文件写入,逐行读入文件,然后后利用key来替换key对应的value。
这里给大家一个完整的代码,大体方法如此,具体的方法大家手动根据自己的需要去改吧。
Java对Properties文件的操作可以说是“不尽人意”,这里时间关系大体先说一下,回头慢慢说。
1.java读Properties文件,经常能读出一些乱码。
2.java写Properties文件,用能把以前的Properties文件的注释弄丢了。
//读配置文件片段
public String getPropertyValue(String key){
Properties pro = new Properties();
try {
InputStream in = new FileInputStream(""); //加载配置文件
try {
pro.load(in);
} finally {
in.close();
}
return pro.getProperty(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//写配置文件片段
public void setPropertyValue(String key, String value){
Properties pro = new Properties();
try {
InputStream in = new FileInputStream(""); //加载配置文件
try {
pro.load(in);
} finally {
in.close();
}
pro.setProperty(key, value);
OutputStream out =new FileOutputStream(""); //加载配置文件
try{
pro.store(out, "modi by lmy");
out.flush();
}finally{
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
上面的[b]public String getPropertyValue(String key)[/b]是不存在什么问题的,因为毕竟就是一个读取操作,但是[b]public void setPropertyValue(String key, String value)[/b]会出现很严重的问题,因为它会把你文件中所有的注释都忽略掉,你保存文件后发现所有的注释都没有了,解决这个问题我找了好多资料,没有什么好办法。最好利用了一个笨办法,就是写入操作不用Properties类机型操作,而是直接利用文件写入,逐行读入文件,然后后利用key来替换key对应的value。
这里给大家一个完整的代码,大体方法如此,具体的方法大家手动根据自己的需要去改吧。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.table.TableModel;
import com.peraglobal.core.AnalyserMap;
public class PropertyTool {
private static Object[][] content;
public final static void setProperty(Properties pro) {
List<String> keys = new ArrayList<String>();
List<String> values = new ArrayList<String>();
content = null;
Iterator<Map.Entry<Object, Object>> it = pro.entrySet().iterator();
String tempValue = "";
Object key;
Object value;
while (it.hasNext()) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it
.next();
// Object key = entry.getKey();
key = entry.getKey();
value = entry.getValue();
keys.add(String.valueOf(key));
try {
tempValue = new String(String.valueOf(value).getBytes(
"iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
values.add(tempValue);
}
content = new Object[keys.size()][2];
for (int i = 0; i < keys.size(); i++) {
content[i][0] = keys.get(i);
content[i][1] = values.get(i);
}
}
public final static List<String> getProperties(String filePath) {
try {
// 加载配置文件
List<String> propCont = new ArrayList<String>();
FileInputStream fis = new FileInputStream(filePath);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
BufferedReader bufferedreader = new BufferedReader(isr);
String temp = "";
while ((temp = bufferedreader.readLine()) != null) {
propCont.add(temp);
}
bufferedreader.close();
isr.close();
fis.close();
return propCont;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public final static void saveProperties(String filePath,
List<String> content, TableModel tableValues) {
try {
// 加载配置文件
FileReader file = new FileReader(filePath);
List<String> propCont = new ArrayList<String>();
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath),
"utf-8"));
String temp = "";
while ((temp = bufferedreader.readLine()) != null) {
propCont.add(temp);
}
propCont = tableValutToList(propCont, tableValues);
bufferedreader.close();
file.close();
BufferedWriter br = null;
OutputStream outsm = new FileOutputStream(filePath);
OutputStreamWriter outFileWriter = new OutputStreamWriter(outsm,
"utf-8");
br = new BufferedWriter(outFileWriter);
br.write(listToString(propCont));
br.flush();
outFileWriter.flush();
outsm.flush();
br.close();
outFileWriter.close();
outsm.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static final List<String> tableValutToList(List<String> content,
TableModel tableValues) {
String keyCell;
String valueCell;
String rowContent;
String[] cellContents;
String newContent;
// 以原始的文档为依据开始遍历。
for (int i = 0; i < content.size(); i++) {
rowContent = content.get(i);
// 遍历修改后的数据
for (int j = 0; j < tableValues.getRowCount(); j++) {
keyCell = String.valueOf(tableValues.getValueAt(j, 1));
valueCell = String.valueOf(tableValues.getValueAt(j, 3));
// 找到原始文件相应的值,并覆盖。
if (0 <= rowContent.indexOf(keyCell)) {
cellContents = rowContent.split("=");
// 判断是否合法,不合法则跳出循环(可能需要更严格的判断,来判断是否是注释等)。
if (0 < cellContents.length
&& !cellContents[0].startsWith("#")
&& keyCell.trim().toLowerCase().equals(cellContents[0].trim().toLowerCase())) {
newContent = cellContents[0] + "=" + valueCell;
content.set(i, newContent);
}
}
}
}
return content;
}
public static final String listToString(List<String> list) {
String str = "";
for (int i = 0; i < list.size(); i++) {
str = str + list.get(i) + "\n";
}
return str;
}
/**
* 读取配置文件字段。
*
* @throws Exception
* */
public final static Object[][] loadProperty(String filePath,
AnalyserMap analyserMap) throws Exception {
Properties pro = new Properties();
File curFile = new File(filePath);
if (!curFile.exists()) {
throw new Exception("文件不存在");
}
// 加载配置文件
InputStream in = new FileInputStream(filePath);
try {
pro.load(in);
} finally {
in.close();
}
PropertyTool.setProperty(pro);
Object[][] content = PropertyTool.getProperties();
Object[] temptt;
List<Object[]> contentList = new ArrayList<Object[]>();
String key;
String value;
for (int i = 0; i < content.length; i++) {
key = String.valueOf(content[i][0]);
value = String.valueOf(content[i][1]);
if (!analyserMap.isVisible(key)) {
continue;
}
temptt = new Object[4];
temptt[0] = (i + 1) + "";
temptt[1] = key;
temptt[2] = analyserMap.getCaption(key);
temptt[3] = value;
contentList.add(temptt);
}
Object[][] reContent = new Object[contentList.size()][];
for (int i = 0; i < reContent.length; i++) {
temptt = contentList.get(i);
reContent[i] = temptt;
reContent[i][0] = i + 1 + "";
}
return reContent;
}
/**
* 读取配置文件字段。
*
* @throws Exception
* */
public final static Object[][] loadProperty(String filePath)
throws Exception {
Properties pro = new Properties();
File curFile = new File(filePath);
if (!curFile.exists()) {
throw new Exception("文件不存在");
}
// 加载配置文件
InputStream in = new FileInputStream(filePath);
try {
pro.load(in);
} finally {
in.close();
}
PropertyTool.setProperty(pro);
Object[][] content = PropertyTool.getProperties();
Object[] temptt;
List<Object[]> contentList = new ArrayList<Object[]>();
String key;
String value;
for (int i = 0; i < content.length; i++) {
key = String.valueOf(content[i][0]);
value = String.valueOf(content[i][1]);
temptt = new Object[2];
temptt[0] = key;
temptt[1] = value;
contentList.add(temptt);
}
Object[][] reContent = new Object[contentList.size()][];
for (int i = 0; i < reContent.length; i++) {
temptt = contentList.get(i);
reContent[i] = temptt;
}
return reContent;
}
public final static Object[][] getProperties() {
return content;
}
}
本文介绍Java中Properties类的使用方法,包括读取和修改配置文件的过程。特别关注如何避免读取乱码及写入时丢失注释的问题。
805

被折叠的 条评论
为什么被折叠?



