gpt4 book ai didi

java - 如何在不使用 Java 保存到磁盘的情况下生成 zip 文件?

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:56 24 4
gpt4 key购买 nike

我在内存中生成了许多 BufferedImages,我想将它们压缩成一个 zip 文件,然后再将其作为电子邮件附件发送。如何在不从磁盘读取文件的情况下将文件保存到 zip。

有什么方法可以在不创建临时文件的情况下压缩这些文件?

由于要创建数千个文件,写入磁盘非常耗时。

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cccprog;

import java.awt.Component;
import java.awt.Panel;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JRadioButton;

/**
*
* @author Z
*/
public class N {

public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
JFrame jf = new JFrame();
Panel a = new Panel();

JRadioButton birdButton = new JRadioButton();
birdButton.setSize(100, 100);

birdButton.setSelected(true);
jf.add(birdButton);

getSaveSnapShot(birdButton, i + ".bmp");

}
}

public static BufferedImage getScreenShot(Component component) {

BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
// paints into image's Graphics
component.paint(image.getGraphics());
return image;
}

public static void getSaveSnapShot(Component component, String fileName) throws Exception {
BufferedImage img = getScreenShot(component);
// BufferedImage img = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_BYTE_BINARY);

// write the captured image as a bmp
ImageIO.write(img, "bmp", new File(fileName));
}
}

最佳答案

我不确定您在这里遇到的用例,如果内存中有数千个文件,您可能会很快耗尽内存。

但是,zip 文件通常是用流生成的,因此没有必要将它们临时存储在文件中 - 还不如存储在内存中或直接流式传输到远程接收者(只有一个小的内存缓冲区以避免大的内存缓冲区)内存占用)。

我发现了一个多年前编写的旧 zip 实用程序,并针对您的用例对其进行了轻微修改。它根据文件列表创建一个存储在字节数组中的 zip 文件,该文件也存储在字节数组中。由于您在内存中表示了很多文件,因此我添加了一个小的辅助类 MemoryFile,其中仅包含文件名和一个包含内容的字节数组。哦,我公开了这些字段以避免样板 getter/setter 的东西——当然只是为了在这里节省一些空间。

public class MyZip {

public static class MemoryFile {
public String fileName;
public byte[] contents;
}

public byte[] createZipByteArray(List<MemoryFile> memoryFiles) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
try {
for (MemoryFile memoryFile : memoryFiles) {
ZipEntry zipEntry = new ZipEntry(memoryFile.fileName);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(memoryFile.contents);
zipOutputStream.closeEntry();
}
} finally {
zipOutputStream.close();
}
return byteArrayOutputStream.toByteArray();
}

}

关于java - 如何在不使用 Java 保存到磁盘的情况下生成 zip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18406148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com