JAVA8向zip中添加文件,把三个文件放到一个zip文件中

import java.io.*;

import java.util.zip.*;

public class Example4 {

//writing a zip archive

static ZipOutputStream myZOS;

public static void main(String args[]) {

myZOS = new ZipOutputStream (

new BufferedOutputStream(

new FileOutputStream("code.zip")));

writeOneFile("Example1.java");

writeOneFile("Example2.java");

writeOneFile("Example3.java");

myZOS.close();

}

static void writeOneFile(String name) throws IOException {

ZipEntry myZE = new ZipEntry(name);

myZOS.putNextEntry(myZE);

BufferedReader myBR = new BufferedReader(new FileReader(name));

int c;

while((c = myBR.read()) != -1)//read a char until EOF

myZOS.write(c);

myBR.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Java接口示例,可以将多个图片链接下载到一个zip文件: ```java import java.io.*; import java.net.URL; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ImageDownloader { public static void downloadImagesToZip(List<String> imageUrls, String zipFileName) throws IOException { // Create a ZipOutputStream to write to the zip file ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName)); // Iterate through each image URL and download it to a temporary file for (int i = 0; i < imageUrls.size(); i++) { String imageUrl = imageUrls.get(i); String tempFileName = "temp_" + i + ".jpg"; downloadImage(imageUrl, tempFileName); // Add the temporary file to the zip file File tempFile = new File(tempFileName); ZipEntry zipEntry = new ZipEntry(tempFile.getName()); zipOut.putNextEntry(zipEntry); FileInputStream input = new FileInputStream(tempFile); byte[] buffer = new byte[1024]; int length; while ((length = input.read(buffer)) > 0) { zipOut.write(buffer, 0, length); } input.close(); zipOut.closeEntry(); tempFile.delete(); } // Close the ZipOutputStream zipOut.close(); } private static void downloadImage(String imageUrl, String fileName) throws IOException { URL url = new URL(imageUrl); InputStream input = url.openStream(); OutputStream output = new FileOutputStream(fileName); byte[] buffer = new byte[1024]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } input.close(); output.close(); } } ``` 这个接口接受一个图片链接列表和一个zip文件名作为参数,然后将每个图片链接下载到一个临时文件,再将所有临时文件打包进一个zip文件。调用示例代码如下: ```java List<String> imageUrls = Arrays.asList( "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg" ); String zipFileName = "images.zip"; ImageDownloader.downloadImagesToZip(imageUrls, zipFileName); ``` 这个示例代码,我们将三个图片链接放入一个List,然后将这个List和一个zip文件名传递给ImageDownloader类的静态方法downloadImagesToZip。该方法会自动下载每个图片链接,并将它们打包进一个名为"images.zip"的zip文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值