# properties存储的键值对格式如下
name=ashe
gender=female
前言
Properties是java提供的api,可以用来操作键值对,常用作操作配置文件
该文件常用后缀名为.prop或者.properties
注意中文乱码问题比较烦,暂无全而完美的方法,遇到后再找资料解决
存取键值对的工具类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class TProperties {
/** 设置键值对 */
public static boolean set(String filePath, String key, String value) {
Properties props = new Properties();
props.setProperty(key, value);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
props.store(fos, null);
return true;
} catch (Exception e) {
return false;
} finally {
try {
if (fos != null) fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 取某键对应的值 */
public static String get(String filePath, String key) {
File file;
InputStream is = null;
Properties properties;
try {
file = new File(filePath);
if (!file.exists()) {
return null;
}
is = new FileInputStream(file);
properties = new Properties();
properties.load(is);
return new String(properties.getProperty(key)); // 处理中文乱码
// return new String(properties.getProperty(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); // 处理中文乱码
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (null != is) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** 取所有键值对 */
public static Map<String, String> getAllKV(String filePath) {
File file;
InputStreamReader is = null;
Properties properties;
try {
file = new File(filePath);
if (!file.exists()) {
return null;
}
is = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
properties = new Properties();
properties.load(is);
Map<String, String> map = new HashMap<>();
// way1: use Enumeration to visit the properties
/*Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String value = (String) enumeration.nextElement();
System.out.println(value + "=" + properties.getProperty(value));
}
// way2: use KeySet to visit the properties
Set<Object> keyset = properties.keySet();
Iterator<Object> itr = keyset.iterator();
while (itr.hasNext()) {
String key = itr.next().toString();
System.out.println(key + "=" + properties.getProperty(key));
}*/
// way3: use stringPropertyNames to visit the properties
Set<String> keys = properties.stringPropertyNames();
for (String key : keys) {
map.put(key, properties.getProperty(key));
}
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (null != is) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}