当前位置: 代码迷 >> 综合 >> java批量读取本地json文件并解析数据,插入数据库
  详细解决方案

java批量读取本地json文件并解析数据,插入数据库

热度:98   发布时间:2024-02-23 03:05:20.0
public class CityCardTest {@AutowiredCityCardService cityCardService;@Testpublic void importDb() {//指定要读取文件的路径String path = "C:\\Users\\1.1\\Desktop\\新建文件夹";ArrayList<File> fileList = new ArrayList<>();//调方法 获取所有文件ArrayList<File> allFile = getAllFile(path, fileList);for (int i = 0; i < allFile.size(); i++) {File file = allFile.get(i);try {//读取json文件内容String input = FileUtils.readFileToString(file, "UTF-8");//转移成对象CityCard cityCard = JSONObject.parseObject(input, CityCard.class);//设置额外属性值cityCard.setDelFlag(0);cityCard.setCreateTime(LocalDateTime.now());cityCard.setUpdateTime(LocalDateTime.now());//通过反射获取当前字段和内容,判断如果包含{} replace 然后重新设置Class<? extends CityCard> aClass = cityCard.getClass();Field[] declaredFields = aClass.getDeclaredFields();for (int j = 0; j < declaredFields.length; j++) {Field field = declaredFields[i];// 设置字段可访问, 否则无法访问private修饰的变量值field.setAccessible(true);// 获取字段名称String fieldName = field.getName();// 获取指定对象的当前字段的值Object fieldVal = field.get(cityCard);if (!"".equals(fieldVal) && null != fieldVal) {String s = fieldVal.toString();if (s.contains("{") || s.contains("}")) {String str = s.replace("{", "").replace("}", "");field.set(fieldName, str);}}}boolean save = cityCardService.save(cityCard);System.out.println(save);} catch (IOException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}public ArrayList<File> getAllFile(String path, ArrayList<File> fileList) {//ArrayList<String> files = new ArrayList<String>();boolean flag = false;File file = new File(path);File[] tempList = file.listFiles();for (int i = 0; i < tempList.length; i++) {//判断如果是文件  存入集合if (tempList[i].isFile()) {fileList.add(tempList[i]);}//如果是文件夹  递归调用if (tempList[i].isDirectory()) {getAllFile(tempList[i].getAbsolutePath(), fileList);}}return fileList;}
}