存下来备用
/**
* 读取json文件
*/
public static String readFile(String path) {
BufferedReader reader = null;
String laststr = "";
try {
/**
通过路径获取流文件(注:这种形式能够确保在以jar包形式运行时也可以成功获取到文件,之前
踩过坑,长心长心)**/
InputStream inputStream = new ClassPathResource(path).getInputStream();
//设置字符编码为UTF-8,避免读取中文乱码
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
// 通过BufferedReader进行读取
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr = laststr + tempString;
}
//关闭BufferedReader
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
//不管执行是否出现异常,必须确保关闭BufferedReader
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
/**
* 写入json文件
*/
public static void write(Object object, String url) throws JSONException, IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("JSON对象的Key",JSON.toJSON(object));
writeFile(url, jsonObject.toString());
}
public static void writeFile(String filePath, String sets)
throws IOException {
FileWriter fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
}