可以先用 逗号截取字符串 然后去写入到Properties文件中 然后用反射读取配置文件 根据获得的属性名 设置对应的值
代码
package property;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;
public class MainClass {
public static void main(String[] args) throws IOException,
IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
String userInfo = "userID=12,userName='Zhaomin'";
String[] s = userInfo.split(",");
BufferedWriter bw = new BufferedWriter(new FileWriter(
"E:/heima/src/property/userInfo.properties"));
for (String str : s) {
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
BufferedReader br = new BufferedReader(new FileReader(
"E:/heima/src/property/userInfo.properties"));
Properties pro = new Properties();
pro.load(br);
Set<Object> set = pro.keySet();
UserInfo ui = new UserInfo();
for (Object o : set) {
String key = (String) o;
String value = pro.getProperty(key);
PropertyDescriptor pd = new PropertyDescriptor(key, ui.getClass());
if(pd.getPropertyType().equals(int.class)){
int value1 = Integer.parseInt(value);
Method m = pd.getWriteMethod();
m.invoke(ui,value1);
}
if(pd.getPropertyType().equals(String.class)){
Method m = pd.getWriteMethod();
m.invoke(ui,value);
}
}
System.out.println(ui.getUserID());
System.out.println(ui.getUserName());
}
}
感觉有点麻烦 每次要要判断类型 还有可能你的字符串不规范 应该有更简单的方法 |