Home >Java >Javagetting Started >Java uses json files to import and export database data

Java uses json files to import and export database data

王林
王林forward
2020-11-16 15:34:225628browse

Java uses json files to import and export database data

Background:

At work, we may encounter situations where we need to quickly move some data in one environment to another environment. At this time, we This can be achieved by importing and exporting json files.

(Learning video sharing: java course)

Example:

We export the user information in the database of this environment into a json format file , and then directly copy the json file to another environment and import it into the database, this can achieve our purpose.

Below I will use springboot to build an import and export case of user data information, and implement the import and export functions of single-user and multi-user database information. After reading this article carefully, you will definitely be able to master the core of importing and exporting json files

Preparation work

Requires maven dependency coordinates:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.29</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

User information in the database:

These field information corresponds one-to-one with the UserEntity entity class in Java

Java uses json files to import and export database data

Function implementation

Prepare dependencies and database information After that, we started to build a specific framework for user import and export:

Java uses json files to import and export database data

Import and export single-user and multi-user functions to implement UserUtil

package com.leige.test.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leige.test.entity.UserEntity;
import com.leige.test.entity.UserEntityList;
import com.leige.test.model.ResultModel;
import com.leige.test.service.UserService;
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

public class UserUtil {
    //导入用户
    public static ResultModel importUser(MultipartFile multipartFile, UserService userService) {
        ResultModel resultModel = new ResultModel();
        try {
            // 获取原始名字
            String fileName = multipartFile.getOriginalFilename();
            // 获取后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //先将.json文件转为字符串类型
            File file = new File("/"+ fileName);
            //将MultipartFile类型转换为File类型
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

            //如果是json或者txt文件
            if (".json".equals(suffixName) || ".txt".equals(suffixName)) {

                //再将json字符串转为实体类
                JSONObject jsonObject = JSONObject.parseObject(jsonString);

                UserEntity userEntity = JSONObject.toJavaObject(jsonObject, UserEntity.class);

                userEntity.setId(null);
                userEntity.setToken(UUID.randomUUID().toString());
                //调用创建用户的接口
                userService.addUser(userEntity);

            } else {
                resultModel.setStatusCode(0);
                resultModel.setStatusMes("请上传正确格式的.json或.txt文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultModel;
    }
    //批量导入用户
    public static ResultModel importUsers(MultipartFile multipartFile, UserService userService) {
        ResultModel resultModel = new ResultModel();
        try {
            // 获取原始名字
            String fileName = multipartFile.getOriginalFilename();
            // 获取后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //先将.json文件转为字符串类型
            File file = new File("/"+ fileName);
            //将MultipartFile类型转换为File类型
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

            //如果是json或者txt文件
            if (".json".equals(suffixName) || ".txt".equals(suffixName)) {

                //再将json字符串转为实体类
                JSONObject jsonObject = JSONObject.parseObject(jsonString);

                UserEntityList userEntityList = JSONObject.toJavaObject(jsonObject, UserEntityList.class);

                List<UserEntity> userEntities = userEntityList.getUserEntities();
                for (UserEntity userEntity : userEntities) {
                    userEntity.setId(null);
                    userEntity.setToken(UUID.randomUUID().toString());
                    //调用创建用户的接口
                    userService.addUser(userEntity);
                }
            } else {
                resultModel.setStatusCode(0);
                resultModel.setStatusMes("请上传正确格式的.json或.txt文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultModel;
    }
    //导出某个用户
    public static ResultModel exportUser(HttpServletResponse response, UserEntity userEntity, String fileName){
        ResultModel resultModel = new ResultModel();
        ObjectMapper objectMapper = new ObjectMapper();
        if (ObjectUtils.isEmpty(userEntity)){
            resultModel.setStatusCode(0);
            resultModel.setStatusMes("此用户id没有对应的用户");
            return resultModel;
        }else {
            try {
                String jsonString = objectMapper.writeValueAsString(userEntity);

                // 拼接文件完整路径// 生成json格式文件
                String fullPath = "/" + fileName;

                // 保证创建一个新文件
                File file = new File(fullPath);
                if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
                    file.getParentFile().mkdirs();
                }
                if (file.exists()) { // 如果已存在,删除旧文件
                    file.delete();
                }
                file.createNewFile();//创建新文件

                //将字符串格式化为json格式
                jsonString = jsonFormat(jsonString);
                // 将格式化后的字符串写入文件
                Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                write.write(jsonString);
                write.flush();
                write.close();

                FileInputStream fis = new FileInputStream(file);
                // 设置相关格式
                response.setContentType("application/force-download");
                // 设置下载后的文件名以及header
                response.setHeader("Content-Disposition", "attachment;filename="
                        .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
                response.setCharacterEncoding("utf-8");
                // 创建输出对象
                OutputStream os = response.getOutputStream();
                // 常规操作
                byte[] buf = new byte[1024];
                int len = 0;
                while((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();
                os.close();  //一定要记得关闭输出流,不然会继续写入返回实体模型
                return resultModel;
            } catch (Exception e) {
                resultModel.setStatusCode(0);
                resultModel.setStatusMes(e.getMessage());
                e.printStackTrace();
                return resultModel;
            }
        }
    }
    //导出所有用户
    public static ResultModel exportAllUser(HttpServletResponse response, UserEntityList userEntityList, String fileName){
        ResultModel resultModel = new ResultModel();
        ObjectMapper objectMapper = new ObjectMapper();
        if (ObjectUtils.isEmpty(userEntityList)){
            resultModel.setStatusCode(0);
            resultModel.setStatusMes("此用户id没有对应的用户");
            return resultModel;
        }else {
            try {
                String jsonString = objectMapper.writeValueAsString(userEntityList);

                // 拼接文件完整路径// 生成json格式文件
                String fullPath = "/" + fileName;

                // 保证创建一个新文件
                File file = new File(fullPath);
                if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
                    file.getParentFile().mkdirs();
                }
                if (file.exists()) { // 如果已存在,删除旧文件
                    file.delete();
                }
                file.createNewFile();//创建新文件

                //将字符串格式化为json格式
                jsonString = jsonFormat(jsonString);
                // 将格式化后的字符串写入文件
                Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                write.write(jsonString);
                write.flush();
                write.close();

                FileInputStream fis = new FileInputStream(file);
                // 设置相关格式
                response.setContentType("application/force-download");
                // 设置下载后的文件名以及header
                response.setHeader("Content-Disposition", "attachment;filename="
                        .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
                response.setCharacterEncoding("utf-8");
                // 创建输出对象
                OutputStream os = response.getOutputStream();
                // 常规操作
                byte[] buf = new byte[1024];
                int len = 0;
                while((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();
                os.close();     //一定要记得关闭输出流,不然会继续写入返回实体模型
                return resultModel;
            } catch (Exception e) {
                resultModel.setStatusCode(0);
                resultModel.setStatusMes(e.getMessage());
                e.printStackTrace();
                return resultModel;
            }
        }
    }
    //将字符串格式化为json格式的字符串
    public static String jsonFormat(String jsonString) {
        JSONObject object= JSONObject.parseObject(jsonString);
        jsonString = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        return jsonString;
    }
}

1. Start the project and enter in the browser Visit http://localhost:8888/export/users to export all existing user json files

Java uses json files to import and export database data

##2. Open the json file to check whether the format is correct

Java uses json files to import and export database data

3. Enter the browser to access http://localhost:8888/ to import users in batches

Import users.json file

Java uses json files to import and export database data

Enter the address and click Submit

Java uses json files to import and export database data

Check the database and find that the two added test users 1 and 2 were successful!

Java uses json files to import and export database data

Import and export of a single user will not be tested here, it is simpler, and other information about the springboot configuration file and the database information corresponding to the entity class will not be explained in detail.

Related recommendations:

Getting started with java

The above is the detailed content of Java uses json files to import and export database data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete