1、工具类
import java.io.*;/*** @Author: jiee* @Date: 2020/8/6 9:49*/
public class JsonUtil {/*** 从文件中读取数据** @param path 文件路径* @return 文件内容*///从给定位置读取Json文件public static String readJson(String path) {//从指定位置读取文件File file = new File(path);BufferedReader br = null;//返回值,使用StringBufferStringBuffer data = new StringBuffer();try {br = new BufferedReader(new FileReader(file));//每次读取文件的缓存String temp = null;while ((temp = br.readLine()) != null) {data.append(temp);
// System.out.println(data);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//关闭文件流if (br != null) {try {br.close();} catch (IOException e) {e.printStackTrace();}}}
// System.out.println("读取成功!");return data.toString();}/*** 向文件中写入数据** @param path 文件路径* @param json json数据* @param fileName 文件名称* @param directoryPath 文件夹名称 * C盘根目录不让创建文件,只能先创建文件夹,在文件夹里创建文件*/public static void writeJson(String path, String directoryPath, Object json, String fileName) {BufferedWriter bw = null;File file = new File(path + fileName);// 创建文件夹File directory = new File(directoryPath);boolean created = directory.mkdir();
// if (created) {
// System.out.println("文件夹创建成功");
// } else {
// System.out.println("文件夹创建失败");
// }//如果文件不存在,则新建一个if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}//写入数据try {bw = new BufferedWriter(new FileWriter(file));bw.write(json.toString());} catch (IOException e) {e.printStackTrace();} finally {try {if (bw != null) {bw.close();}} catch (IOException e) {e.printStackTrace();}}
// System.out.println("写入成功!");}}
2、创建文件,并写入,及读取
在需要的地方调用此工具类
// 此代码的思路是,如果从前端获取不到ip,就从文本里读取String fileName="js.txt";String path="D:\\js\\";String directoryPath = "D:\\js";JSONObject jsonObject = new JSONObject();jsonObject.put("ip", ip);String json = null;if(ip == "" || ip == null){//调用读的方法json = JsonUtil.readJson("D:\\js\\js.txt");JSONObject jsonIp = JSON.parseObject(json);ip = (String)jsonIp.get("ip");}else {// 调用写的方法JsonUtil.writeJson(path,directoryPath,jsonObject,fileName);}
最终在D盘创建一个js文件夹,在js文件夹内创建一个js的txt文本