Java 通过url下载文件并压缩

import org.apache.tools.zip.ZipOutputStream
import org.apache.tools.zip.ZipEntry


@ApiOperation(value = "下载文件链接")    
@RequestMapping(value = "/getDownload", method = RequestMethod.POST)
public void downloadCERService(HttpServletResponse response) throws IOException {
        String url = "";
        ArrayList<String> strings = new ArrayList<>();
        strings.add(url);
        // 配置文件下载
        response.setCharacterEncoding("UTF-8"); //设置编码字符
        response.setContentType("application/octet-stream;charset=UTF-8");
        //压缩包文件名
        SimpleDateFormat fileZipName = new SimpleDateFormat("yyyyMMddhhmmss");
        // 下载文件时候防止显示中文乱码 指定文件类型 .zip
        response.setHeader("Content-Disposition", "attachment;filename=" + 
        URLEncoder.encode(fileZipName.format(new Date()) + ".zip", "UTF-8"));
        getZipFile(getByte(strings), response.getOutputStream());
    }
public static void getZipFile(Map<String, byte[]> stringByte, OutputStream outputStream) throws IOException {
        //将文件打包成压缩文件
        ZipOutputStream zipout = new ZipOutputStream(outputStream);
         zipout.setEncoding("GBK");   //解决文件名中文乱码
        Set<Map.Entry<String, byte[]>> dataEntrys = stringByte.entrySet();
        for (Map.Entry<String, byte[]> data : dataEntrys) {
            InputStream bufferIn = new BufferedInputStream(new 
            ByteArrayInputStream(data.getValue()));
            byte[] bs = new byte[1024];
            Arrays.fill(bs, (byte) 0);
            //创建压缩文件内的文件
           ZipEntry zipEntry  = new ZipEntry(data.getKey())
            zipout.putNextEntry(zipEntry);
            //zipEntry.setUnixMode(755);//解决linux乱码
            //zipEntry.setUnixMode(644);//解决linux乱码
            int len = -1;
            while ((len = bufferIn.read(bs)) > 0) {
                zipout.write(bs, 0, len);
            }
            bufferIn.close();
        }
        try {
            zipout.close();
        } catch (IOException e) {
        }
    }

public static Map<String, byte[]> getByte(List<String> urlPath) {
        Map<String, byte[]> stringMap = new HashMap<String, byte[]>();
        byte[] data = new byte[1024];
        ByteArrayOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            for (String string : urlPath) {
                //根据文件访问地址获取输入流
                URL url = new URL(string);
                URLConnection urlConnection = url.openConnection();
                inputStream = urlConnection.getInputStream();
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                stringMap.put("2022.docx", outputStream.toByteArray());
            }
            return stringMap;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中,要根据URL获取文件,并按文件夹进行分类并压缩打包,可以使用一些常见的类库和方法来实现。 首先,我们需要使用Java的网络编程来获取指定URL文件。可以使用URLURLConnection类来建立连接,并使用输入流将文件内容读取到内存中。如果需要处理HTTPS协议,还需要使用HttpsURLConnection类。 接下来,我们需要对获取的文件进行按文件夹分类。可以通过解析URL中的路径信息来提取文件夹路径,然后创建对应的文件夹。可以使用java.nio.file包下的Path和Files类来处理文件路径和创建文件夹。 然后,我们需要将分类后的文件进行压缩打包。可以使用Java压缩库,如java.util.zip包下的ZipOutputStream类来创建压缩文件,并使用FileOutputStream将压缩文件写入磁盘。可以先获取每个文件的输入流,然后使用ZipEntry将文件放入压缩文件中。 最后,记得在完成操作后关闭打开的资源,如关闭输入流和输出流。 下面是一个简单的示例代码,演示如何根据URL获取文件,按文件夹分类并压缩打包: ```java import java.io.*; import java.net.URL; import java.nio.file.*; import java.util.zip.*; public class FileDownloader { public static void main(String[] args) { String urlPath = "http://example.com/path/to/files/"; String savePath = "C:/save/"; String zipFilePath = "C:/save/archive.zip"; try { // 创建连接 URL url = new URL(urlPath); InputStream inputStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); // 解析路径并创建文件夹 Path saveDir = Paths.get(savePath); Files.createDirectories(saveDir); // 创建压缩文件 FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zipOut = new ZipOutputStream(fos); // 读取文件并分类 String line; while ((line = reader.readLine()) != null) { // 解析文件名和路径 String fileName = line.substring(line.lastIndexOf("/") + 1); String folderPath = line.substring(urlPath.length(), line.lastIndexOf("/")); // 创建分类文件夹 Path folderDir = saveDir.resolve(folderPath); Files.createDirectories(folderDir); // 将文件放入压缩文件 ZipEntry zipEntry = new ZipEntry(folderPath + "/" + fileName); zipOut.putNextEntry(zipEntry); // 写入文件内容 byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { zipOut.write(buffer, 0, bytesRead); } } // 关闭资源 reader.close(); zipOut.close(); fos.close(); System.out.println("文件下载、分类和压缩打包完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,上述代码只是简单示例,实际使用中可能还需要进行错误处理、异常捕获和其他特殊需求的处理。同时,也可以根据具体情况进行优化和调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值