我正在创建一个Java程序,它从JFileChooser获取图像并创建包含所选图像的.zip文件。我用这段代码获取文件:
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileFilter(new FileNameExtensionFilter("Image files", "bmp", "png", "jpg"));
fc.setAcceptAllFileFilterUsed(false);
fc.showOpenDialog(null);
File files[] = fc.getSelectedFiles();
我如何创建包含files[]
数组文件的.zip文件?
感谢您的帮助:D。
答案 0 :(得分:0)
File someFile = new File("someFile.zip");
File files[] = fc.getSelectedFiles();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(someFile));
// Create the ZIP file first
try (ZipOutputStream out = new ZipOutputStream(bos)) {
// Write files/copy to archive
for (File file : files) {
// Put a new ZIP entry to output stream for every file
out.putNextEntry(new ZipEntry(file.getName()));
Files.copy(file.toPath(), out);
out.closeEntry();
}
}