java实现文件打包_Java实现文件自动打包成zip并下载的代码

package www.gjw.test;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

import javax.imageio.stream.FileImageInputStream;

public class Test

{

public static void main(String[] args) throws Exception

{

byte[] buffer = new byte[1024];

// 生成的ZIP文件名为Demo.zip

String strZipName = "Demo.zip";

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));

// 需要同时下载的两个文件result.txt ,source.txt

File[] file1 = { new File("C:/log_client.txt"), new File("C:/360AppLoader.exe"), new File("C:/56656.txt")};

for (int i = 0; i < file1.length; i++)

{

FileInputStream fis = new FileInputStream(file1[i]);

out.putNextEntry(new ZipEntry(file1[i].getName()));

int len;

// 读入需要下载的文件的内容,打包到zip文件

while ((len = fis.read(buffer)) > 0)

{

out.write(buffer, 0, len);

}

out.closeEntry();

fis.close();

}

out.close();

System.out.println("生成Demo.zip成功");

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2013-09-24 15:34

浏览 1245

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用`java.util.zip`包来实现根据URL将多个文件打包zip并进行下载的功能。下面是一个示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipDownloader { public static void main(String[] args) { String zipUrl = "http://example.com/files.zip"; String[] fileUrls = {"http://example.com/file1.txt", "http://example.com/file2.txt"}; try { // 创建ZipOutputStream FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 从URL下载并添加文件zip中 for (String fileUrl : fileUrls) { URL url = new URL(fileUrl); InputStream is = url.openStream(); zos.putNextEntry(new ZipEntry(url.getFile())); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); // 下载zip文件 downloadZip(zipUrl); } catch (IOException e) { e.printStackTrace(); } } private static void downloadZip(String url) throws IOException { URL zipUrl = new URL(url); InputStream is = zipUrl.openStream(); FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } is.close(); fos.close(); } } ``` 上述代码首先创建了一个`ZipOutputStream`对象,然后依次遍历多个文件的URL,将每个文件下载后添加到zip中,并关闭流。最后调用`downloadZip`方法根据zip文件的URL进行下载。请确保提供的URL和文件格式的可用性和正确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值