我已经在内存中生成了许多BufferedImages,我想在将它们作为电子邮件附件发送之前将它们压缩到一个zip文件中。如何在不从磁盘读取文件的情况下将文件保存为zip文件。如何在不保存到Java磁盘的情况下生成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));
}
}
看看java.utli.zip。 –
为了我的好奇心,为什么要避免创建临时文件? – 2013-08-23 15:09:39
这似乎相关http://stackoverflow.com/questions/7108035/how-to-flush-the-zipoutputstream-periodically-in-java – Ted