Java 生成zip压缩包

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tools.zip.ZipOutputStream;

public String createZip(String path,String fileName,String xxdm){
  String zipFileName = xxdm + ".zip";
   byte[] buf = new byte[1024];
   try {
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path + zipFileName));
    FileInputStream in = new FileInputStream(path + fileName);
    out.putNextEntry(new org.apache.tools.zip.ZipEntry(fileName));
    int len;
    while ((len = in.read(buf)) > 0)
    {
     out.write(buf, 0, len);
    }
    out.closeEntry();
    in.close();
    out.close();
     }catch (IOException e)
     {
      e.printStackTrace();
     }
  
       
  return zipFileName;
 } 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java提供的ZipOutputStream类来创建一个zip压缩文件,然后将下载的文件添加到该压缩文件中。下面是一段示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class DownloadAndZip { public static void main(String[] args) throws Exception { // 下载文件 URL url = new URL("http://example.com/file.txt"); InputStream in = url.openStream(); FileOutputStream fos = new FileOutputStream("file.txt"); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { fos.write(buffer, 0, length); } in.close(); fos.close(); // 创建zip文件并添加下载的文件到其中 FileOutputStream fosZip = new FileOutputStream("file.zip"); ZipOutputStream zipOut = new ZipOutputStream(fosZip); File fileToZip = new File("file.txt"); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int lengthZip; while ((lengthZip = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, lengthZip); } fis.close(); zipOut.closeEntry(); zipOut.close(); fosZip.close(); } } ``` 在上面的示例中,我们首先从指定的URL下载文件并保存到本地文件“file.txt”中。接下来,我们创建一个ZipOutputStream对象,并将下载的文件添加到其中。最后,我们将ZipOutputStream写入到一个新的文件“file.zip”中,并关闭所有的输入和输出流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值