亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁 Java Java入門 java利用json檔案來實現(xiàn)資料庫資料的導入導出

java利用json檔案來實現(xiàn)資料庫資料的導入導出

Nov 16, 2020 pm 03:34 PM
java json 資料庫

java利用json檔案來實現(xiàn)資料庫資料的導入導出

背景:

工作中我們可能會遇到需要將某個環(huán)境中的某些資料快速的移動到另一個環(huán)境的情況,此時我們就可以透過匯入導出json檔案的方式實現(xiàn)。

(學習影片分享:java課程

範例:

我們將這個環(huán)境的資料庫中使用者資訊匯出為一份json格式文件,再直接將json檔案複製到另一個環(huán)境匯入到資料庫,這樣可以達到我們的目的。

下面我將使用springboot建立使用者資料資訊的導入?yún)R出案例,實作了單一使用者和多使用者資料庫資訊的導入?yún)R出功能。認真看完這篇文章,你一定能掌握導入導出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檔案來實現(xiàn)資料庫資料的導入導出

#功能實作

準備好依賴與資料庫信息之後,開始建立使用者匯入?yún)R出特定框架:

java利用json檔案來實現(xiàn)資料庫資料的導入導出

匯入?yún)R出單使用者、多使用者功能實作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)資料庫資料的導入導出

2、開啟json檔案檢視格式是否正確

java利用json檔案來實現(xiàn)資料庫資料的導入導出

java利用json檔案來實現(xiàn)資料庫資料的導入導出

java利用json檔案來實現(xiàn)資料庫資料的導入導出

java利用json檔案來實現(xiàn)資料庫資料的導入導出

##3、瀏覽器輸入存取http://localhost:8888/ 批次匯入使用者

匯入users.json 檔案############## #輸入位址,點選提交###############查看資料庫,發(fā)現(xiàn)增加的兩個測試使用者1,2成功! ###############導入?yún)R出單一使用者這裡就不測試了,更加簡單,其他的關於springboot設定檔和實體類別對應資料庫資訊也不詳細說明了。 ######相關推薦:###java入門######

以上是java利用json檔案來實現(xiàn)資料庫資料的導入導出的詳細內(nèi)容。更多資訊請關注PHP中文網(wǎng)其他相關文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔相應的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
VSCODE設置。 JSON位置 VSCODE設置。 JSON位置 Aug 01, 2025 am 06:12 AM

settings.json文件位於用戶級或工作區(qū)級路徑,用於自定義VSCode設置。 1.用戶級路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級路徑:項目根目錄下的.vscode/settings

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務,必須先關閉自動提交模式,再執(zhí)行多個操作,最後根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開始事務;2.執(zhí)行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時應使用try-with-resources管理資源,妥善處理異常並關閉連接,避免連接洩漏;此外建議使用連接池、設置保存點實現(xiàn)部分回滾,並保持事務盡可能短以提升性能。

在Java的掌握依賴注入春季和Guice 在Java的掌握依賴注入春季和Guice Aug 01, 2025 am 05:53 AM

依賴性(di)IsadesignpatternwhereObjectsReceivedenciesenciesExtern上,推廣looseSecouplingAndEaseerTestingThroughConstructor,setter,orfieldInjection.2.springfraMefringframeWorkSannotationsLikeLikeLike@component@component,@component,@service,@autowiredwithjava-service和@autowiredwithjava-ligatiredwithjava-lase-lightike

Python Itertools組合示例 Python Itertools組合示例 Jul 31, 2025 am 09:53 AM

itertools.combinations用於生成從可迭代對像中選取指定數(shù)量元素的所有不重複組合(順序無關),其用法包括:1.從列表中選2個元素組合,如('A','B')、('A','C')等,避免重複順序;2.對字符串取3個字符組合,如"abc"、"abd",適用於子序列生成;3.求兩數(shù)之和等於目標值的組合,如1 5=6,簡化雙重循環(huán)邏輯;組合與排列的區(qū)別在於順序是否重要,combinations視AB與BA為相同,而permutations視為不同;

Python Pytest夾具示例 Python Pytest夾具示例 Jul 31, 2025 am 09:35 AM

fixture是用於為測試提供預設環(huán)境或數(shù)據(jù)的函數(shù),1.使用@pytest.fixture裝飾器定義fixture;2.在測試函數(shù)中以參數(shù)形式註入fixture;3.yield之前執(zhí)行setup,之後執(zhí)行teardown;4.通過scope參數(shù)控製作用域,如function、module等;5.將共用fixture放在conftest.py中實現(xiàn)跨文件共享,從而提升測試的可維護性和復用性。

故障排除常見的java`ofmemoryError`場景'' 故障排除常見的java`ofmemoryError`場景'' Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError:Javaheapspace表示堆內(nèi)存不足,需檢查大對象處理、內(nèi)存洩漏及堆設置,通過堆轉(zhuǎn)儲分析工具定位並優(yōu)化代碼;2.Metaspace錯誤因類元數(shù)據(jù)過多,常見於動態(tài)類生成或熱部署,應限制MaxMetaspaceSize並優(yōu)化類加載;3.Unabletocreatenewnativethread因係統(tǒng)線程資源耗盡,需檢查線程數(shù)限制、使用線程池、調(diào)整棧大小;4.GCoverheadlimitexceeded指GC頻繁但回收少,應分析GC日誌,優(yōu)化

如何使用Java的日曆? 如何使用Java的日曆? Aug 02, 2025 am 02:38 AM

使用java.time包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當前日期時間;3.使用of()方法創(chuàng)建特定日期時間;4.利用plus/minus方法不可變地增減時間;5.使用ZonedDateTime和ZoneId處理時區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

如何在崇高文本中格式化json 如何在崇高文本中格式化json Jul 31, 2025 am 09:08 AM

toformatjsoninsublimeText,F(xiàn)irstensureTheStaxIstaXistoJsonViaViaview→語法→JSON.2.USETHEBUILT-INREINDENTENTENTCOMMANDENTCOMMANDWITHCTRL ALT B(Windows/linux)orcmd ctrl ctrl b(Mac)Toformatthejson.3.ForenhancedFeaturesLikeValidationandSorting,installtheprettyjsonpluginvi

See all articles