选择多个文件,系统运行后自动生成ZIP压缩包
实现方法
案例简述:通过启动java代码来打开文件选择器对话框,用户选择确认需要进行压缩的文件,可一次性选择多个文件,选择完毕后点击按钮确认,指定位置自动生成压缩包。
1.1 代码块
import javax.imageio.stream.FileImageInputStream;
import javax.swing.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
public class FileZipper {
//生成文件名
public static String GenerateFileName(String filePath,String suffix){
String filename;
Date date = new Date();
SimpleDateFormat dsf = new SimpleDateFormat("yyyyMMddHHss");
filename = filePath + dsf.format(date) + " temp" +suffix;
return filename;
}
//选择多个文件,生成压缩包
public static void FileZipperByMulties() throws FileNotFoundException {
String filePath = "D:\\JAVAFILE\\attachments\\rars\\";
JFileChooser fileChooser = new JFileChooser("C:\\Users\\ASUS-PC\\Desktop\\csdn");
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setDialogTitle("请选择要压缩的文件(可选择多个)");
fileChooser.setApproveButtonText("确定");
int value = fileChooser.showOpenDialog(null);
if(value != JFileChooser.APPROVE_OPTION){
return;
}
File outZipFile = new File(GenerateFileName(filePath,".zip"));
File[] files = fileChooser.getSelectedFiles();
try(ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(outZipFile))){
for(File file:files){
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
try(FileImageInputStream fileImageInputStream = new FileImageInputStream(file)) {
byte[] bytes = new byte[1024];
int length;
while((length = fileImageInputStream.read(bytes))>0){
zipOutputStream.write(bytes,0,length);
}
}
}
zipOutputStream.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
try{
FileZipperByMulties();
System.out.println("File compressed successfully!");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
1.2 运行结果截取
- 文件选择器对话框选择多个文件
- 控制台输出,表示执行正确
- 压缩包信息