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

Java uses json files to import and export database data

Nov 16, 2020 pm 03:34 PM
java json database

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

'Java is not recognized' Error in CMD [3 Simple Steps] 'Java is not recognized' Error in CMD [3 Simple Steps] Aug 23, 2025 am 01:50 AM

IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.

See all articles