溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java如何利用json文件來實現數據庫數據的導入導出

發布時間:2020-11-17 10:09:33 來源:億速云 閱讀:770 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關java如何利用json文件來實現數據庫數據的導入導出,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

背景:

工作中我們可能會遇到需要將某個環境中的某些數據快速的移動到另一個環境的情況,此時我們就可以通過導入導出json文件的方式實現。

舉例:

我們將這個環境的數據庫中用戶信息導出為一份json格式文件,再直接將json文件復制到另一個環境導入到數據庫,這樣可以達到我們的目的。

下面我將使用springboot搭建用戶數據信息的導入導出案例,實現了單用戶和多用戶數據庫信息的導入導出功能。認真看完這篇文章,你一定能掌握導入導出json文件的核心

準備工作

需要maven依賴坐標:

        <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>

數據庫中的用戶信息:

這些字段信息與Java中的UserEntity實體類一一對應

java如何利用json文件來實現數據庫數據的導入導出

功能實現

準備好依賴和數據庫信息之后,開始搭建用戶導入導出具體框架:

java如何利用json文件來實現數據庫數據的導入導出

導入導出單用戶、多用戶功能實現 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、啟動項目,瀏覽器輸入訪問 http://localhost:8888/export/users 導出所有已有用戶json文件

java如何利用json文件來實現數據庫數據的導入導出

2、打開json文件查看格式是否正確

java如何利用json文件來實現數據庫數據的導入導出

3、瀏覽器輸入訪問 http://localhost:8888/ 批量導入用戶

導入 users.json 文件

java如何利用json文件來實現數據庫數據的導入導出

輸入地址,點擊提交

java如何利用json文件來實現數據庫數據的導入導出

查看數據庫,發現增加的兩條測試用戶1,2成功!

java如何利用json文件來實現數據庫數據的導入導出

導入導出單個用戶這里就不測試了,更加簡單,其他的關于springboot配置文件和實體類對應數據庫信息也不詳細說明了。

關于java如何利用json文件來實現數據庫數據的導入導出就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女