最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實(shí)現(xiàn)批量導(dǎo)出導(dǎo)入數(shù)據(jù)及附件文件zip包

 更新時(shí)間:2022年09月22日 16:12:42   作者:舉杯同慶  
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)批量導(dǎo)出導(dǎo)入數(shù)據(jù)及附件文件zip包的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一

前言-應(yīng)用場(chǎng)景

某系統(tǒng)在不同單位使用時(shí)存在兩套生產(chǎn)環(huán)境,他們的數(shù)據(jù)不是互通的,所以這些單位的上一級(jí)領(lǐng)導(dǎo)部門在統(tǒng)計(jì)數(shù)據(jù)的時(shí)候希望將A系統(tǒng)的數(shù)據(jù)和附件信息導(dǎo)出到一個(gè)壓縮包里,然后把這個(gè)壓縮包一鍵導(dǎo)入到B系統(tǒng),這樣B系統(tǒng)就包含了全部的數(shù)據(jù),上級(jí)領(lǐng)導(dǎo)就能看到全部的業(yè)務(wù)信息,便于統(tǒng)計(jì)分析。

一、導(dǎo)出ZIP包

1. 列表數(shù)據(jù)導(dǎo)出到本地excel文件

        String path = profile + "/temp/" + DateUtils.dateTimeNow();
        File file = new File(path);
        if (file.mkdirs()) {
            System.out.println("文件夾創(chuàng)建成功!創(chuàng)建后的文件目錄為:" + file.getPath());
        }
        //1. 輸出Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet");
        String fileName="XX數(shù)據(jù)導(dǎo)出.xls";
        String savePath= file.getPath() + File.separator +fileName;
        OutputStream os = new FileOutputStream(savePath);
        //響應(yīng)到客戶端(即瀏覽器端直接彈出下載連接的方式)需要用response獲取流
        //this.setResponseHeader(response, filename);
        //OutputStream os = response.getOutputStream();
        List<HashMap> dataList = new ArrayList<>();
        try{
            // 表頭
            this.createExcelTitle(workbook, sheet);
            // 查詢條件
            HashMap param = this.buildQueryParams(params);
            dataList = shareRegisterMapper.shareList(param);
            if (CollectionUtils.isEmpty(dataList)){
                return;
            }
            this.dealAssetData(dataList, sheet);
            // 處理子表數(shù)據(jù)
            this.dealAssetDetailData(dataList,workbook);
            workbook.write(os);
            os.flush();
            os.close();
        }catch(Exception e) {
            e.printStackTrace();

???????        }finally {
            if (os != null) {
                os.flush();
                os.close();
            }
            workbook.close();
        }

2. 下載附件信息

在上一步生成的Excel文件路徑下新建files文件夾,里面存放附件

public void downloadFile(List<HashMap> dataList) throws Exception {
    String urlPrefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    String savePath = file.getPath() + File.separator + "/files";
        OutputStream os = null;
        InputStream is = null;
        int i=0;
        try {
            for (HashMap data : dataList) {
                if (data == null || data.get("FILES") == null){
                    continue;
                }
                List<ZsglFileEntity> entityList = new ArrayList<>();
                String[] fileArray = data.get("FILES").toString().split(",");
                List idList = Arrays.asList(fileArray);
                entityList.addAll(fileMapper.selectByIds(idList));
                if (CollectionUtils.isNotEmpty(entityList)){
                    for (ZsglFileEntity file : entityList){
                        if ( file.getFssFileId() == null){
                            continue;
                        }
                        String fileUrl = urlPrefix + "/fss/download/" + file.getFssFileId();
                        // 構(gòu)造URL
                        URL url = new URL(fileUrl);
                        // 打開連接
                        URLConnection con = url.openConnection();
                        //設(shè)置請(qǐng)求超時(shí)為5s
                        con.setConnectTimeout(5 * 1000);
                        // 輸入流
                        is = con.getInputStream();
                        File tempFile = new File(savePath + "/"+file.getFileName());
                        // 校驗(yàn)文件夾目錄是否存在,不存在就創(chuàng)建一個(gè)目錄
                        if (!tempFile.getParentFile().exists()) {
                            tempFile.getParentFile().mkdirs();
                        }
                        os = new FileOutputStream(tempFile);
                        is = con.getInputStream();
                        con.getHeaderFields();
                        IOUtils.copy(is, os);
                        System.out.println("下載完成");
                    }
                    entityList.clear();
                }
            }
        }catch (IOException e){
            System.err.println(e);
        }finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }

3. 生成壓縮文件(瀏覽器下載)

        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("content-disposition", "attachment;filename=" + "XX數(shù)據(jù)導(dǎo)出.zip");
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        try {
            File[] sourceFiles = file.listFiles();
            if (null == sourceFiles || sourceFiles.length < 1) {
                System.out.println("待壓縮的文件目錄:" + "里面不存在文件,無(wú)需壓縮.");
            } else {
                for (int i = 0; i < sourceFiles.length;i++){
                    File srcFile = sourceFiles[i];
                    if (srcFile.isDirectory()){
                        File[] imageSourceFiles = srcFile.listFiles();
                        if (null == imageSourceFiles || imageSourceFiles.length < 1){
                            continue;
                        }
                        for (File imageFile : imageSourceFiles){
                            compress(zos,imageFile,srcFile.getName()+"/");
                        }
                    } else {
                        compress(zos,srcFile,"");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            //關(guān)閉流
            try {
                if(null != zos) {
                    zos.close();
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }

其中的壓縮方法如下:

public void compress(ZipOutputStream out,File sourceFile,String base) throws Exception
    {
        out.putNextEntry( new ZipEntry(base+sourceFile.getName()) );
        FileInputStream fos = new FileInputStream(sourceFile);
        BufferedInputStream bis = new BufferedInputStream(fos);
        int tag;
        System.out.println(base);
        //將源文件寫入到zip文件中
        while((tag=bis.read())!=-1) {
            out.write(tag);
            out.flush();
        }
        out.closeEntry();
        bis.close();
        fos.close();
    }

4. 刪除臨時(shí)目錄

public void deleteDirectory(File file) {
        File[] list = file.listFiles();  //無(wú)法做到list多層文件夾數(shù)據(jù)
        if (list != null) {
            for (File temp : list) {     //先去遞歸刪除子文件夾及子文件
                deleteDirectory(temp);   //注意這里是遞歸調(diào)用
            }
        }
        if (!file.delete()) {     //再刪除自己本身的文件夾
            logger.error("文件刪除失敗 : %s%n", file);
        }
    }

二、導(dǎo)入ZIP包

1. 上傳zip包,解壓到臨時(shí)目錄

這里開始想著在不解壓的情況下讀取里面的文件,結(jié)果沒有走通。因?yàn)閦ip里面包含了子文件夾里面的附件信息需要解析。不解壓直接解析文件適用于只需要解析zip包中第一層文件的場(chǎng)景,如果子文件夾下的文件也需要處理的話,最好解壓后再處理。

public void unzip(ZipInputStream zipIn, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        ZipEntry entry = zipIn.getNextEntry();
        // 遍歷Zip文件中的條目
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                int index = entry.getName().indexOf("/");
                if (index > -1 && entry.getName().length() > index){
                    File tempFile = new File(destDirectory + File.separator +entry.getName().substring(0,index));
                    if (!tempFile.exists()){
                        tempFile.mkdir();
                    }
                }
                File checkFile = new File(filePath);
                if (!checkFile.exists()) {
                    checkFile.createNewFile();// 創(chuàng)建目標(biāo)文件
                }
                // 如果條目是文件直接解壓
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = new byte[1024];
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                File dir = new File(filePath);
                if (!dir.exists()){
                    dir.mkdirs();
                }
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }

這里解壓遇到了一個(gè)問(wèn)題,之前導(dǎo)出生成的zip包直接導(dǎo)入沒問(wèn)題,但是我把導(dǎo)出的包手動(dòng)解壓后修改了部分?jǐn)?shù)據(jù)重新壓縮后再導(dǎo)入報(bào)錯(cuò):ZipInputStream解壓遠(yuǎn)程文件報(bào)錯(cuò),java.lang.IllegalArgumentException: MALFORMED

原因:文件名含有中文,zip解析出錯(cuò)

解決方案,如下行代碼,在生成ZipInputStream的時(shí)候指定編碼格式。

ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputStream), Charset.forName(“GBK”));

2. 讀取附件信息上傳到文件服務(wù)器

public List<HashMap> readLocalFile() throws Exception {
        File file= new File(destDirectory+"/files");
        List<HashMap> fssList = new ArrayList<>();
        if (file.exists()) {
            File[] sourceFiles = file.listFiles();
            if (null == sourceFiles || sourceFiles.length < 1) {
                System.out.println(file.getName()+"目錄里面不存在文件,無(wú)需處理.");
                return fssList;
            } else {
                for (int i = 0; i < sourceFiles.length;i++){
                    File srcFile = sourceFiles[i];
                    FileItemFactory factory = new DiskFileItemFactory(16, null);
                    FileItem item = factory.createItem(srcFile.getName(), "text/plain", true, srcFile.getName());
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    try {
                        FileInputStream fis = new FileInputStream(srcFile);
                        OutputStream os = item.getOutputStream();
                        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }
                        os.close();
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    MultipartFile mfile = new CommonsMultipartFile(item);
                    AjaxResult fileResult = this.fssFileService.uploadFile(mfile);
                    String filePath = fileResult.get("url") == null ? "" : fileResult.get("url").toString();
                    if (fileResult.get("fileId") != null){
                        HashMap tempMap = new HashMap();
                        String fileId = this.fileService.saveFileInfo(fileResult.get("fileId").toString(),mfile, filePath, "");
                        tempMap.put(srcFile.getName(), fileId);
                        fssList.add(tempMap);
                    }
                }
            }
        }
        return fssList;
    }

注意:這里有個(gè)小難點(diǎn)就是File轉(zhuǎn)換成MultipartFile的方法,因?yàn)轫?xiàng)目中已經(jīng)有的上傳文件是MultipartFile格式的,轉(zhuǎn)換一下就不用在實(shí)現(xiàn)一遍上傳方法了。

3. 讀取Excel文件存入數(shù)據(jù)庫(kù)

我是用EasyExcel導(dǎo)入Excel文件的,代碼很簡(jiǎn)單,需要注意用EasyExcel導(dǎo)入的Excel文件如果包含多個(gè)sheet頁(yè),需要寫多個(gè)導(dǎo)入監(jiān)聽文件。

4. 刪除臨時(shí)文件

這一步實(shí)現(xiàn)方法跟導(dǎo)出時(shí)相同,去掉臨時(shí)文件。

以上就是Java實(shí)現(xiàn)批量導(dǎo)出導(dǎo)入數(shù)據(jù)及附件文件zip包的詳細(xì)內(nèi)容,更多關(guān)于Java導(dǎo)出導(dǎo)入數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java自旋鎖和JVM對(duì)鎖的優(yōu)化詳解

    java自旋鎖和JVM對(duì)鎖的優(yōu)化詳解

    這篇文章主要為大家介紹了java自旋鎖和JVM對(duì)鎖的優(yōu)化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • 淺談SpringMVC請(qǐng)求映射handler源碼解讀

    淺談SpringMVC請(qǐng)求映射handler源碼解讀

    這篇文章主要介紹了淺談SpringMVC請(qǐng)求映射handler源碼解讀,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • SpringBoot前后端傳輸加密設(shè)計(jì)實(shí)現(xiàn)方案

    SpringBoot前后端傳輸加密設(shè)計(jì)實(shí)現(xiàn)方案

    這篇文章主要給大家介紹了關(guān)于SpringBoot前后端傳輸加密設(shè)計(jì)實(shí)現(xiàn)方案的相關(guān)資料,包括數(shù)據(jù)加密方案、解密傳輸數(shù)據(jù)實(shí)現(xiàn)方案和響應(yīng)數(shù)據(jù)加密實(shí)現(xiàn)方案,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-11-11
  • Java基礎(chǔ)學(xué)習(xí)之集合底層原理

    Java基礎(chǔ)學(xué)習(xí)之集合底層原理

    今天帶大家回顧Java基礎(chǔ)的相關(guān)知識(shí),文中對(duì)集合底層原理作了非常詳細(xì)的圖文介紹,對(duì)Java初學(xué)者有非常好的幫助,需要的朋友可以參考下
    2021-05-05
  • 詳解SpringCloud-OpenFeign組件的使用

    詳解SpringCloud-OpenFeign組件的使用

    這篇文章主要介紹了SpringCloud-OpenFeign組件的使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • resttemplate設(shè)置params的方法

    resttemplate設(shè)置params的方法

    RestTemplate設(shè)置請(qǐng)求參數(shù)的方式根據(jù)請(qǐng)求類型(GET/POST)和參數(shù)形式(路徑參數(shù)、查詢參數(shù)、JSON請(qǐng)求體)有所不同,下面通過(guò)本文給大家介紹resttemplate設(shè)置params的方法,感興趣的朋友一起看看吧
    2025-04-04
  • Spring Boot整合MybatisPlus逆向工程(MySQL/PostgreSQL)

    Spring Boot整合MybatisPlus逆向工程(MySQL/PostgreSQL)

    MyBatis-Plus是MyBatis的增強(qiáng)工具,本文主要介紹了Spring Boot整合MybatisPlus逆向工程(MySQL/PostgreSQL),具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-07-07
  • restTemplate未設(shè)置連接數(shù)導(dǎo)致服務(wù)雪崩問(wèn)題以及解決

    restTemplate未設(shè)置連接數(shù)導(dǎo)致服務(wù)雪崩問(wèn)題以及解決

    面對(duì)線上問(wèn)題,仔細(xì)分析原因,及時(shí)調(diào)整配置,能有效解決問(wèn)題,本文詳細(xì)描述了線上遇到流量突增引發(fā)的問(wèn)題,通過(guò)查看代碼和連接池信息,分析出問(wèn)題的原因是連接池滿了,連接池大小配置不足以應(yīng)對(duì)大并發(fā)流量,通過(guò)調(diào)整連接池大小配置
    2024-10-10
  • 兼容Spring Boot 1.x和2.x配置類參數(shù)綁定的工具類SpringBootBindUtil

    兼容Spring Boot 1.x和2.x配置類參數(shù)綁定的工具類SpringBootBindUtil

    今天小編就為大家分享一篇關(guān)于兼容Spring Boot 1.x和2.x配置類參數(shù)綁定的工具類SpringBootBindUtil,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-12-12
  • 基于JavaMail API收發(fā)郵件的方法

    基于JavaMail API收發(fā)郵件的方法

    這篇文章主要介紹了基于JavaMail API收發(fā)郵件的方法,實(shí)例分析了javamail的使用方法與相關(guān)注意事項(xiàng),非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2015-07-07

最新評(píng)論

宁海县| 广德县| 平远县| 布拖县| 汽车| 汝城县| 报价| 泸溪县| 阆中市| 文化| 固安县| 兰西县| 友谊县| 临颍县| 台山市| 惠州市| 休宁县| 许昌市| 宾川县| 永登县| 福贡县| 南平市| 石家庄市| 正镶白旗| 昌图县| 化隆| 右玉县| 会泽县| 咸丰县| 宁城县| 泽州县| 镇安县| 新昌县| 宁强县| 永德县| 亳州市| 剑川县| 衡阳市| 新巴尔虎左旗| 双柏县| 原平市|