根据您的需要,可能有数百种方法可以解决此问题,但从我的角度来看,您想要做的是用尽可能少的代码行说“将此文件夹压缩到此 zip 文件”...
为此,我可以更改代码以允许您执行以下操作:
ZipUtils appZip = new ZipUtils();
appZip.zipIt(new File(source), new File(output));
指某东西的用途File
参数的含义没有任何歧义。这种机制还意味着您可以调用zipIt
根据您的需要一次又一次地进行,而无需创建新的实例ZipUtils
这将需要对基本代码进行一些修改,因为它假设String
文件路径的值,坦率地说,这简直令人发狂,因为您真正想要的所有信息都可以更轻松地从File
对象-恕我直言。这也意味着您根本不需要维护对源路径的引用,超出了范围zipIt
method
public static class ZipUtils {
private final List<File> fileList;
private List<String> paths;
public ZipUtils() {
fileList = new ArrayList<>();
paths = new ArrayList<>(25);
}
public void zipIt(File sourceFile, File zipFile) {
if (sourceFile.isDirectory()) {
byte[] buffer = new byte[1024];
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
String sourcePath = sourceFile.getPath();
generateFileList(sourceFile);
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
FileInputStream in = null;
for (File file : this.fileList) {
String path = file.getParent().trim();
path = path.substring(sourcePath.length());
if (path.startsWith(File.separator)) {
path = path.substring(1);
}
if (path.length() > 0) {
if (!paths.contains(path)) {
paths.add(path);
ZipEntry ze = new ZipEntry(path + "/");
zos.putNextEntry(ze);
zos.closeEntry();
}
path += "/";
}
String entryName = path + file.getName();
System.out.println("File Added : " + entryName);
ZipEntry ze = new ZipEntry(entryName);
zos.putNextEntry(ze);
try {
in = new FileInputStream(file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
} finally {
in.close();
}
}
zos.closeEntry();
System.out.println("Folder successfully compressed");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
protected void generateFileList(File node) {
// add file only
if (node.isFile()) {
fileList.add(node);
}
if (node.isDirectory()) {
File[] subNote = node.listFiles();
for (File filename : subNote) {
generateFileList(filename);
}
}
}
}
ps- You public static void main
,不是有效的“主入口点”,它应该是public static void main(String[] args)
;)
因此,根据您的代码片段,您可以简单地执行以下操作:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
String zipName = name+ "_" + dateFormat.format(date) + ".zip";
zippedFile = new File(archive, zipName);
if (zippedFile exists()) {
zippedFile.delete();
}
ZipUtils zu = new ZipUtils();
zu.zipIt(dirToZip, zippedFile);