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

Java實(shí)現(xiàn)批量下載文件的示例代碼

 更新時間:2023年10月27日 10:51:16   作者:西瓜喵  
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)批量下載文件,并以壓縮輸出流的形式返回前端,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考一下

我需要調(diào)取第三方接口的數(shù)據(jù)存到本地服務(wù)器上,然后在以輸出流的形式響應(yīng)

zipUtil(工具類,直接復(fù)制即可,這個是我從別的博主那里復(fù)制來的,親測有效)

 public class ZipUtil {
 
        private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
 
        // 目錄標(biāo)識判斷符
        public static final String PATCH = "/";
        // 基目錄
        public static final String BASE_DIR = "";
        // 緩沖區(qū)大小
        private static final int BUFFER = 2048;
        // 字符集
        public static final String CHAR_SET = "GBK";
 
 
        /**
         *
         * 描述: 壓縮文件
         * @author wanghui
         * @created 2017年10月27日
         * @param fileOutName
         * @param files
         * @throws Exception
         */
        public static void compress(String fileOutName, List<File> files) throws Exception {
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(fileOutName);
                ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
                zipOutputStream.setEncoding(CHAR_SET);
 
                if (files != null && files.size() > 0) {
                    for (int i = 0,size = files.size(); i < size; i++) {
                        compress(files.get(i), zipOutputStream, BASE_DIR);
                    }
                }
                // 沖刷輸出流
                zipOutputStream.flush();
                // 關(guān)閉輸出流
                zipOutputStream.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
 
        /**
         *
         * 描述:壓縮文件并進(jìn)行Base64加密
         * @author wanghui
         * @created 2017年10月27日
         * @param files
         * @return
         * @throws Exception
         */
        public static String compressToBase64(List<File> files) throws Exception {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
                zipOutputStream.setEncoding(CHAR_SET);
 
                if (files != null && files.size() > 0) {
                    for (int i = 0,size = files.size(); i < size; i++) {
                        compress(files.get(i), zipOutputStream, BASE_DIR);
                    }
                }
                // 沖刷輸出流
                zipOutputStream.flush();
                // 關(guān)閉輸出流
                zipOutputStream.close();
 
                byte[] data = bos.toByteArray();
                return new String(Base64.encodeBase64(data));
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
        /**
         *
         * 描述: 壓縮
         * @author wanghui
         * @created 2017年10月27日
         * @param srcFile
         * @param zipOutputStream
         * @param basePath
         * @throws Exception
         */
        public static void compress(File srcFile, ZipOutputStream zipOutputStream, String basePath) throws Exception {
            if (srcFile.isDirectory()) {
                compressDir(srcFile, zipOutputStream, basePath);
            } else {
                compressFile(srcFile, zipOutputStream, basePath);
            }
        }
 
        /**
         *
         * 描述:壓縮目錄下的所有文件
         * @author wanghui
         * @created 2017年10月27日
         * @param dir
         * @param zipOutputStream
         * @param basePath
         * @throws Exception
         */
        private static void compressDir(File dir, ZipOutputStream zipOutputStream, String basePath) throws Exception {
            try {
                // 獲取文件列表
                File[] files = dir.listFiles();
 
                if (files.length < 1) {
                    ZipEntry zipEntry = new ZipEntry(basePath + dir.getName() + PATCH);
 
                    zipOutputStream.putNextEntry(zipEntry);
                    zipOutputStream.closeEntry();
                }
 
                for (int i = 0,size = files.length; i < size; i++) {
                    compress(files[i], zipOutputStream, basePath + dir.getName() + PATCH);
                }
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            }
        }
 
        /**
         *
         * 描述:壓縮文件
         * @author wanghui
         * @created 2017年10月27日
         * @param file
         * @param zipOutputStream
         * @param dir
         * @throws Exception
         */
        private static void compressFile(File file, ZipOutputStream zipOutputStream, String dir) throws Exception {
            try {
                // 壓縮文件
                ZipEntry zipEntry = new ZipEntry(dir + file.getName());
                zipOutputStream.putNextEntry(zipEntry);
 
                // 讀取文件
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
 
                int count = 0;
                byte data[] = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    zipOutputStream.write(data, 0, count);
                }
                bis.close();
                zipOutputStream.closeEntry();
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
        /**
         *
         * 描述: 文件Base64加密
         * @author wanghui
         * @created 2017年10月27日 上午9:27:38
         * @param srcFile
         * @return
         * @throws Exception
         */
        public static String encodeToBASE64(File srcFile) throws Exception {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                // 讀取文件
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
 
                int count = 0;
                byte data[] = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    bos.write(data, 0, count);
                }
                bis.close();
 
                byte[] base64Data = Base64.encodeBase64(bos.toByteArray());
                if (null == base64Data) {
                    bos.close();
                    return null;
                }
 
                bos.close();
                return new String(base64Data, CHAR_SET);
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
        /**
         *
         * 描述: 文件Base64解密
         * @author wanghui
         * @created 2017年10月27日
         * @param destFile
         * @param encodeStr
         * @throws Exception
         */
        public static void decodeToBase64(File destFile, String encodeStr) throws Exception {
            try {
                byte[] decodeBytes = Base64.decodeBase64(encodeStr.getBytes());
 
                ByteArrayInputStream bis = new ByteArrayInputStream(decodeBytes);
                // 讀取文件
                FileOutputStream fileOutputStream = new FileOutputStream(destFile);
 
                int count = 0;
                byte data[] = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    fileOutputStream.write(data, 0, count);
                }
                fileOutputStream.close();
                bis.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
        /**
         *
         * 描述: 解壓縮
         * @author wanghui
         * @created 2017年10月27日
         * @param srcFileName
         * @param destFileName
         * @throws Exception
         */
        @SuppressWarnings("unchecked")
        public static void decompress(String srcFileName, String destFileName)  throws Exception {
            try {
                ZipFile zipFile = new ZipFile(srcFileName);
                Enumeration<ZipEntry> entries = zipFile.getEntries();
                File destFile = new File(destFileName);
                InputStream inputStream = null;
 
                while(entries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry)entries.nextElement();
                    String dir = destFile.getPath() + File.separator + zipEntry.getName();
                    File dirFile = new File(dir);
 
                    if (zipEntry.isDirectory()) {
                        dirFile.mkdirs();
                    } else {
                        fileProber(dirFile);
                        inputStream = zipFile.getInputStream(zipEntry);
                        decompressFile(dirFile, inputStream);
                    }
                }
                zipFile.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage(),e);
            }
        }
 
        /**
         *
         * 描述: 解壓文件
         * @author wanghui
         * @created 2017年10月27日
         * @param destFile
         * @param inputStream
         * @throws Exception
         */
        private static void decompressFile(File destFile, InputStream inputStream) throws Exception {
            try {
                // 文件輸入流
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
 
                int count = 0;
                byte data[] = new byte[BUFFER];
                while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
                    bos.write(data, 0, count);
                }
                bos.close();
                inputStream.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            }
        }
 
        /**
         *
         * 描述:文件探測
         * @author wanghui
         * @created 2017年10月27日
         * @param dirFile
         */
        private static void fileProber(File dirFile) {
            File parentFile = dirFile.getParentFile();
            if (!parentFile.exists()) {
                // 遞歸尋找上級目錄  
                fileProber(parentFile);
                parentFile.mkdir();
            }
        }
    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     * @param dir 將要刪除的文件目錄
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
           //遞歸刪除目錄中的子目錄下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時為空,可以刪除
        return dir.delete();
    }

Controller層

public void bathDownScript(HttpServletResponse response, String paths) throws Exception {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
	    //1.新建文件夾,用來存放下載下來的文件,最后進(jìn)行壓縮
           File folder = new File("/tmp/"+uuid);
           System.out.println(folder.getName());
            if (!folder.exists() && !folder.isDirectory()) {
                boolean flag = folder.mkdirs();
            }
         //2.遍歷讀取文件放入文件夾中
         String[] path= paths.split(",");
         Configuration conf = new Configuration();
         conf.set("fs.defaultFS", HdfsUtils.HDFSURL);
         List<File> files = new ArrayList<File>();
		  for(String huePath:path){
		      //通過hdfs讀取文件
		      byte[] res = HdfsUtils.readFile(conf,huePath);
		      //定義文件名稱
              String fileName = huePath.substring(huePath.lastIndexOf("/"));
              //定義文件路徑
              File f = new File("/tmp/"+uuid+fileName);
              InputStream in = new ByteArrayInputStream(res);
              byte[] buff = new byte[1024];
              FileOutputStream out = new FileOutputStream(f);
              try {
                  int i = in.read(buff);
                  while (i != -1) {
                      out.write(buff, 0, buff.length);
                      out.flush();
                      i = in.read(buff);
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  if (in != null) {
                      try {
                          in.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
                files.add(f);
          }
        //3.響應(yīng)前端數(shù)據(jù)
        String zipName = "myfile.zip";
        response.setHeader("content-type", "application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 設(shè)置瀏覽器響應(yīng)頭對應(yīng)的Content-disposition
        response.setHeader("Content-disposition",
                "attachment;filename=" + new String(zipName.getBytes("gbk"), "iso8859-1"));
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
            zipOutputStream.setEncoding(ZipUtil.CHAR_SET);
           if (CollectionUtils.isEmpty(files) == false) {
             for (int i = 0,size = files.size(); i < size; i++) {
                ZipUtil.compress(files.get(i), zipOutputStream, ZipUtil.BASE_DIR);
            }
        }
          // 沖刷輸出流
           zipOutputStream.flush();
        // 關(guān)閉輸出流
         zipOutputStream.close();
   //4.下載完刪除deleteDir
       boolean flag =  ZipUtil.deleteDir(folder);
        System.out.println("刪除文件:"+flag);
}

以上就是Java實(shí)現(xiàn)批量下載文件的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Java批量下載文件的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java線程數(shù)究竟設(shè)多少合理

    Java線程數(shù)究竟設(shè)多少合理

    這篇文章主要介紹了Java線程數(shù)究竟設(shè)多少合理,對線程感興趣的同學(xué),可以參考下
    2021-04-04
  • SpringBoot 如何根據(jù)不同profile選擇不同配置

    SpringBoot 如何根據(jù)不同profile選擇不同配置

    這篇文章主要介紹了SpringBoot 如何根據(jù)不同profile選擇不同配置的操作方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • java8根據(jù)某一屬性過濾去重的實(shí)例

    java8根據(jù)某一屬性過濾去重的實(shí)例

    這篇文章主要介紹了java8根據(jù)某一屬性過濾去重的實(shí)例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Java25 模式匹配增強(qiáng)的代碼實(shí)現(xiàn)

    Java25 模式匹配增強(qiáng)的代碼實(shí)現(xiàn)

    模式匹配是Java 14+引入的重要特性,Java 25 進(jìn)一步增強(qiáng)了模式匹配的能力,Java 25 的模式匹配增強(qiáng)為我們提供了更強(qiáng)大、更靈活的代碼表達(dá)能力,本文就來詳細(xì)的介紹一下Java25 模式匹配的實(shí)現(xiàn),感興趣的可以了解一下
    2026-04-04
  • SpringBoot整合Mybatis-Plus實(shí)現(xiàn)關(guān)聯(lián)查詢

    SpringBoot整合Mybatis-Plus實(shí)現(xiàn)關(guān)聯(lián)查詢

    Mybatis-Plus(簡稱MP)是一個Mybatis的增強(qiáng)工具,只是在Mybatis的基礎(chǔ)上做了增強(qiáng)卻不做改變,MyBatis-Plus支持所有Mybatis原生的特性,本文給大家介紹了SpringBoot整合Mybatis-Plus實(shí)現(xiàn)關(guān)聯(lián)查詢,需要的朋友可以參考下
    2024-08-08
  • 動力節(jié)點(diǎn)_王勇_DRP項(xiàng)目視頻教程完整版292集

    動力節(jié)點(diǎn)_王勇_DRP項(xiàng)目視頻教程完整版292集

    該視頻由國內(nèi)知名講師王勇老師主講,適合掌握J(rèn)ava基礎(chǔ)內(nèi)容的同學(xué)學(xué)習(xí),本視頻共計292集,學(xué)習(xí)Java Web項(xiàng)目,DRP項(xiàng)目視頻是首選,累計下載量已經(jīng)達(dá)到上千萬,很多同學(xué)通過自學(xué)該視頻找到了軟件開發(fā)工作
    2017-04-04
  • 基于SpringBoot實(shí)現(xiàn)用戶身份驗(yàn)證工具

    基于SpringBoot實(shí)現(xiàn)用戶身份驗(yàn)證工具

    這篇文章主要介紹了基于SpringBoot實(shí)現(xiàn)的用戶身份驗(yàn)證工具,非常不錯,具有參考借鑒價值 ,需要的朋友可以參考下
    2018-04-04
  • java中常用的字符串的比較方法(兩種)

    java中常用的字符串的比較方法(兩種)

    本文主要介紹了java中兩種常用的字符串的比較方法。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03
  • mapstruct中的@Mapper注解的基本用法

    mapstruct中的@Mapper注解的基本用法

    在MapStruct中,@Mapper注解是核心注解之一,用于標(biāo)記一個接口或抽象類為MapStruct的映射器(Mapper),本文給大家介紹mapstruct中的@Mapper注解的相關(guān)知識,感興趣的朋友一起看看吧
    2025-06-06
  • WebUploader實(shí)現(xiàn)圖片上傳功能

    WebUploader實(shí)現(xiàn)圖片上傳功能

    這篇文章主要為大家詳細(xì)介紹了WebUploader實(shí)現(xiàn)圖片上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-03-03

最新評論

信阳市| 鄂州市| 灵武市| 林西县| 武冈市| 平昌县| 万荣县| 平阳县| 芷江| 揭东县| 当雄县| 集安市| 普陀区| 兴仁县| 丹棱县| 靖江市| 巧家县| 万年县| 丰县| 榆中县| 和田县| 沙坪坝区| 吉首市| 五峰| 安吉县| 墨竹工卡县| 湖南省| 夏津县| 疏附县| 修文县| 长宁区| 余姚市| 通山县| 桓台县| 陆良县| 巩留县| 凯里市| 兴海县| 河西区| 岳池县| 哈尔滨市|