package com.docus.bgts.entity; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.util.StringUtils; import java.io.*; public class TableJsonRead { /** * 读取数据结构 * @param path 路径后缀 * @param fileName 文件名称 * @return */ public T Read(String path,String fileName,Class clazz){ String currentPath=CurrentPath(); path = currentPath+"\\"+path; StringBuilder sb = new StringBuilder(); T dto =null; File file = new File(path+"\\"+fileName); try { if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { BufferedReader bufferedReader = null; bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; while (!StringUtils.isEmpty(line = bufferedReader.readLine())) { sb.append(line); } if (sb.length() > 0) { ObjectMapper objectMapper = new ObjectMapper(); //dto = (T)JSONObject.parse(sb.toString()); dto= objectMapper.readValue(sb.toString(), clazz); //dto = objectMapper.convertValue(o, new TypeReference() { }); } bufferedReader.close(); } return dto; } catch (Exception ex){ ex.printStackTrace(); return null; } } /** * 取得当前jar路径 * @return */ private String CurrentPath(){ File dir = new File("."); String currentpath =""; try { currentpath = dir.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } return currentpath; } /** * 保存json至文件 * @param path 路径后缀 * @param fileName 文件名称 * @param data json信息 * @return */ public void Save(String path,String fileName,String data){ String currentPath=CurrentPath(); path = currentPath+"\\"+path; FileWriter fwriter = null; try { fwriter = new FileWriter(path+"\\"+fileName); fwriter.write(data); } catch (IOException ex) { ex.printStackTrace(); } finally { try { fwriter.flush(); fwriter.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }