import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @Author suzhiwen
* @create 2020/3/19
*/
public class FileCompress {
private static final String FILEPATH = "C:\\Users\\suzhiwen-pc\\Desktop\\AAA";
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("文件1", "111");
map.put("文件2", "222");
map.put("文件3", "333");
createFile(map, FILEPATH);
generateFile(new File(FILEPATH), "rar");
}
public static void createFile(Map<String, String> map, String dirDest) throws Exception {
// 模拟 将map内容写到本地txt
File file = new File(dirDest);
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!file.isDirectory()) {
file.mkdir();
}
FileOutputStream outputStream = new FileOutputStream(file + File.separator + entry.getKey() + ".txt");
// ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Utils.decodeFromString(PDF_BASE64));
ByteArrayInputStream inputStream = new ByteArrayInputStream(entry.getValue().getBytes());
// 进行写操作
int len = 0;
byte[] bytes = new byte[8192];
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
// 关闭输入流
inputStream.close();
outputStream.close();
}
}
public static void generateFile(File file, String format) throws Exception {
// 压缩文件的路径不存在
if (!file.exists()) {
throw new Exception("路径 " + file.getAbsolutePath() + " 不存在文件,无法进行压缩...");
}
// 目的压缩文件
String generateFileName = file.getAbsolutePath() + "." + format;
FileOutputStream outputStream = new FileOutputStream(generateFileName);
// 压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
generateFile(zipOutputStream, file, "");
System.out.println("目的压缩文件生成位置:" + generateFileName);
// 关闭 输出流
zipOutputStream.close();
}
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
// 当前的是文件夹,则进行一步处理
if (file.isDirectory()) {
//得到文件列表信息
File[] files = file.listFiles();
//将文件夹添加到下一级打包目录
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
//循环将文件夹中的文件打包
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
}
} else { // 当前是文件
// 输入流
FileInputStream inputStream = new FileInputStream(file);
// 标记要打包的条目
out.putNextEntry(new ZipEntry(dir));
// 进行写操作
int len = 0;
byte[] bytes = new byte[8192];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
// 关闭输入流
inputStream.close();
}
}
}