java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

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

成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設,塔城企業(yè)網(wǎng)站建設,塔城品牌網(wǎng)站建設,網(wǎng)站定制,塔城網(wǎng)站建設報價,網(wǎng)絡營銷,網(wǎng)絡優(yōu)化,塔城網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。

背景:

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

舉例:

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

下面我將使用springboot搭建用戶數(shù)據(jù)信息的導入導出案例,實現(xiàn)了單用戶和多用戶數(shù)據(jù)庫信息的導入導出功能。認真看完這篇文章,你一定能掌握導入導出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>

數(shù)據(jù)庫中的用戶信息:

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

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

功能實現(xiàn)

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

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

導入導出單用戶、多用戶功能實現(xiàn) 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文件轉(zhuǎn)為字符串類型
            File file = new File("/"+ fileName);
            //將MultipartFile類型轉(zhuǎn)換為File類型
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

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

                //再將json字符串轉(zhuǎn)為實體類
                JSONObject jsonObject = JSONObject.parseObject(jsonString);

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

                userEntity.setId(null);
                userEntity.setToken(UUID.randomUUID().toString());
                //調(diào)用創(chuàng)建用戶的接口
                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文件轉(zhuǎn)為字符串類型
            File file = new File("/"+ fileName);
            //將MultipartFile類型轉(zhuǎn)換為File類型
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
            String jsonString = FileUtils.readFileToString(file, "UTF-8");

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

                //再將json字符串轉(zhuǎn)為實體類
                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());
                    //調(diào)用創(chuàng)建用戶的接口
                    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;

                // 保證創(chuàng)建一個新文件
                File file = new File(fullPath);
                if (!file.getParentFile().exists()) { // 如果父目錄不存在,創(chuàng)建父目錄
                    file.getParentFile().mkdirs();
                }
                if (file.exists()) { // 如果已存在,刪除舊文件
                    file.delete();
                }
                file.createNewFile();//創(chuàng)建新文件

                //將字符串格式化為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");
                // 創(chuàng)建輸出對象
                OutputStream os = response.getOutputStream();
                // 常規(guī)操作
                byte[] buf = new byte[1024];
                int len = 0;
                while((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();
                os.close();  //一定要記得關閉輸出流,不然會繼續(xù)寫入返回實體模型
                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;

                // 保證創(chuàng)建一個新文件
                File file = new File(fullPath);
                if (!file.getParentFile().exists()) { // 如果父目錄不存在,創(chuàng)建父目錄
                    file.getParentFile().mkdirs();
                }
                if (file.exists()) { // 如果已存在,刪除舊文件
                    file.delete();
                }
                file.createNewFile();//創(chuàng)建新文件

                //將字符串格式化為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");
                // 創(chuàng)建輸出對象
                OutputStream os = response.getOutputStream();
                // 常規(guī)操作
                byte[] buf = new byte[1024];
                int len = 0;
                while((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                fis.close();
                os.close();     //一定要記得關閉輸出流,不然會繼續(xù)寫入返回實體模型
                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文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

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

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

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

導入 users.json 文件

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

輸入地址,點擊提交

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

查看數(shù)據(jù)庫,發(fā)現(xiàn)增加的兩條測試用戶1,2成功!

java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出

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

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

當前標題:java如何利用json文件來實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)的導入導出
網(wǎng)頁鏈接:http://www.muchs.cn/article28/ijsecp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設軟件開發(fā)、小程序開發(fā)、Google、虛擬主機、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設計