public static boolean deleteKeyValue4Pro(String delete_key, String delete_value, String filePath) {
boolean flag = false;
String toreplace =delete_key + "=" + delete_value + "\n";
try {
StringBuffer sb = new StringBuffer();
String templine;
File file = new File(filePath);
BufferedReader bin = new BufferedReader(new FileReader(file));
while ((templine = bin.readLine()) != null) {
templine = unicodeToString(templine);
sb.append(templine + "\n");
}
String save = new String(sb.toString());
System.out.println("before delete:\n" + save + "\n--------------\n");
System.out.println("delete:" + toreplace + "\n--------------\n");
Pattern pattern = Pattern.compile(toreplace, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(save);
while (matcher.find()) {
save = matcher.replaceAll("");
}
// 写回,我想字符串save里既然包含了换行,应该可以直接写回吧;
//抱着试试看的心理,没想到可以用;(对于上面的代码不明觉历);
FileOutputStream output=new FileOutputStream(file);
byte [] buff=new byte[]{};
buff=save.getBytes();
output.write(buff, 0, buff.length);
output.close();
/*网上的写回过程是这样的,总是报错(好像是空指针异常),然后配置文件都被清空了(因为没有写回);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String[] saves = save.split("\n");
for (int i = 0; i < saves.length; i++) {
String[] key_values = saves[i].split("=");
writer.write(stringToUnicode((key_values[0]) + "=" + key_values[1] + "\n"));
}
System.out.println("after delete:\n" + save);
writer.flush();
bin.close();
writer.close();*/
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 将字符串转成unicode
* @param str 待转字符串
* @return unicode字符串
*/
public static String stringToUnicode(String str)
{
str = (str == null ? "" : str);
String tmp;
StringBuffer sb = new StringBuffer(1000);
char c;
int i, j;
sb.setLength(0);
for (i = 0; i < str.length(); i++)
{
c = str.charAt(i);
sb.append("\\u");
j = (c >>>8); //取出高8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);
j = (c & 0xFF); //取出低8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);
}
return (new String(sb));
}
/**
* 将unicode 字符串
* @param str 待转字符串
* @return 普通字符串
*/
public static String unicodeToString(String str)
{
str = (str == null ? "" : str);
if (str.indexOf("\\u") == -1)//如果不是unicode码则原样返回
return str;
StringBuffer sb = new StringBuffer(1000);
for (int i = 0; i < str.length() - 6;)
{
String strTemp = str.substring(i, i + 6);
String value = strTemp.substring(2);
int c = 0;
for (int j = 0; j < value.length(); j++)
{
char tempChar = value.charAt(j);
int t = 0;
switch (tempChar)
{
case 'a':
t = 10;
break;
case 'b':
t = 11;
break;
case 'c':
t = 12;
break;
case 'd':
t = 13;
break;
case 'e':
t = 14;
break;
case 'f':
t = 15;
break;
default:
t = tempChar - 48;
break;
}
c += t * ((int) Math.pow(16, (value.length() - j - 1)));
}
sb.append((char) c);
i = i + 6;
}
return sb.toString();
}
[编辑][Java]删除properties配置文件中键值对的方法、附带字符串和Unicode间的转换方法
最新推荐文章于 2022-03-07 10:52:09 发布