springboot读取json文件进行增删操作
1.读文件
public static JSONArray read(String Path)throws Exception {
BufferedReader reader = null;
JSONArray ret = null;
JSONArray arr = new JSONArray();
try{
File file = new File(Path);
FileInputStream resource = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(resource));
StringBuilder builder = new StringBuilder();
String line ="";
while((line = reader.readLine())!=null) {
builder.append(line);
}
ret = JSON.parseArray(builder.toString());
}catch(Exception e){
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
return arr;
}
在此,filePath可以是本地文件路径(如:C:\xxx.json),也可以是项目中文件路径(src/main/xxx)路径一定要对哦
2.增加操作
此处传递一个可以转换成为JSONAObject的String字符串
public static JSONArray insert(String str, JSONArray arr){
arr.add(JSONObject.parseObject(str));
return arr;
}
此处传递的参数arr即是从上面读文件的操作中得到的JSONArray数组,可以直接通过传参的形式传递过来使用
3.删除操作
此处可以传递一个类似于数据库主键的数据(我这里传递的是id的值),利用迭代器,进行删除操作
public static JSONArray delete(String id, JSONArray arr)throws Exception {
Iterator<Object> it = arr.iterator();
while(it.hasNext()){
JSONObject x = (JSONObject)it.next();
if(x.getString("id").equals(id)){
it.remove();
}
}
return arr;
}
此处传递的参数arr即是从上面读文件的操作中得到的JSONArray数组,可以直接通过传参的形式传递过来使用
4.写入文件
将进行插入或者删除操作后的数据存入json文件中
public static void write(JSONArray arr, String Path) throws Exception {
BufferedWriter writer = null;
try {
String s= JSON.toJSONString(arr, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
File file = new File(Path);
FileOutputStream resource = new FileOutputStream(file, false);
writer = new BufferedWriter(new OutputStreamWriter(resource));
writer.write(s);
}catch(Exception e){
e.printStackTrace();
}finally{
if(writer!=null){
writer.close();
}
}
}
OK,大功告成