[英]image download in zip using java
我试图下载图像作为zip,但当我尝试运行以下代码时,它说“压缩文件夹无效”,当我尝试打开文件夹unsing 7zip或任何其他zip提取器。 请帮忙
public static void main(String[] args) {
FileOutputStream fos;
try {
fos = new FileOutputStream("D:\\update.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
URL url = new URL("http://n3.sdlcdn.com/imgs/b/9/r/SDL468499912_2-8f209.jpg");
ZipEntry ze = new ZipEntry(url.getFile());
zos.putNextEntry(ze);
byte[] data = new byte[300000];
// fos.write(data, 0, data.length);
zos.write(data, 0, data.length);
zos.closeEntry();
zos.finish();
zos.close();
} catch (Exception ex) {
Logger.getLogger(Main77.class.getName()).log(Level.SEVERE, null, ex);
}
}
将图像保存为zip,如下所示。
public class ZipSaveWorker implements Runnable{
public static ZipOutputStream out=null;
BufferedImage myImage;
private static int counter=0;
public void run() {
ZipEntry entry=new ZipEntry("video"+counter+".jpg");
counter++;
try {
out.putNextEntry(entry);
ImageIO.write(myImage, "jpg", out);
} catch (IOException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ZipSaveWorker(BufferedImage image)
{
if (out==null)
{
try {
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File("images" + File.separator + "video.zip"))));
} catch (FileNotFoundException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
counter=0;
}
myImage=image;
}
public static void closeStream()
{
try {
out.flush();
out.close();
} catch (IOException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
并使用任何Imagedownload libarary下载图像
zos.write正在写入字节数组的空白缓冲区。
byte[] data = new byte[300000];
zos.write(data, 0, data.length);
为什么不初始化较小的字节数组并循环下载的图像中接收的实际字节以添加到输出流中?
在http://www.java-examples.com/create-zip-file-directory-using-zipoutputstream-example中查看使用zip输出流的一个很好的示例
读取字节数组中的图像数据,并将字节添加到zipoutputstream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.