存储数据到JSON文件:
User u = new User();
MessageUtil.cache=”D:\\WSE\\Weixin\\”
String path = MessageUtil.cache + "WebContent\\config\\user.json";
JSONObject jo = JSONObject.fromObject(u);
FileWriter writer = new FileWriter(path, true);
writer.write(jo.toString() + ",\r\n");
writer.close();
存储时为续写模式,而非替换。
读取本地JSON文件:
String path = MessageUtil.cache + "WebContent\\config\\user.json";
String sets = ReadFile(path);
JSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象
for (int i = 0; i < ja.size(); i++) {
User u = new User();
jo.get("KEY").toString();
//KEY为User存储时保存的属性。
Return u
}
ReadFile.java:
public static String ReadFile(String path) {
String laststr = "";
File file = new File(path);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
//System.out.println("line " + line + ": " + tempString);
laststr = laststr + tempString;
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
更新本地JSON:
根据条件找到匹配对象,设置更新属性,然后移除源对象,添加新对象,最后在转为JSONARRAY
String path = MessageUtil.cache + "WebContent\\config\\user.json";
String sets = ReadFile(path);// 读取本地json
JSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象
JSONObject newjo = null;
for (int i = 0; i < ja.size(); i++) {
JSONObject jo = ja.getJSONObject(i);
if (jo.get("key").equals(key)) {//匹配条件
User u = (User) JSONObject.toBean(jo, User.class);
u.setToken(token);//需要更新的属性
u.setPassword(password); //需要更新的属性
newjo = JSONObject.fromObject(u);//转为JSON对象
ja.remove(i);// 如果token无效,则删除该记录,
i=i-1;
}
}
ja.add(newjo);
FileWriter fw = new FileWriter(path);
fw.write("");// json文件
fw.close();
FileWriter writer = new FileWriter(path, true);// 重新写入json
for (int i = 0; i < ja.size(); i++) {
writer.write(ja.get(i).toString() + ",\r\n");
}
writer.close();
删除本地JSON数据:
先转为JSONARRAY,进行移除,然后重新写入
String path = MessageUtil.cache + "WebContent\\config\\user.json";
String sets = ReadFile(path);// 读取本地json
JSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象
JSONObject newjo = null;
for (int i = 0; i < ja.size(); i++) {
JSONObject jo = ja.getJSONObject(i);
if (jo.get("key").equals(key)) {
ja.remove(i);// 如果token无效,则删除该记录,
}
}
FileWriter fw;
try {
FileWriter writer = new FileWriter(path, true);// 重新写入json
fw = new FileWriter(path);
fw.write("");// json文件
fw.close();
for (int i = 0; i < ja.size(); i++) {
writer.write(ja.get(i).toString() + ",\r\n");
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}