2 回答
TA贡献1811条经验 获得超4个赞
干得好:
private static void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
zos.close();
}
./
./somethigelse/
./其他东西/
TA贡献1842条经验 获得超12个赞
该解决方案保留了创建的 zip 文件内的文件夹结构的层次结构 -
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipDirectories {
public static void main(String[] args) throws IOException {
zipDirectory(args[0], args[1]);
}
private static void zipDirectory(String zipFileName, String rootDirectoryPath) throws IOException {
File directoryObject = new File(rootDirectoryPath);
if (!zipFileName.endsWith(".zip")) {
zipFileName = zipFileName + ".zip";
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
System.out.println("Creating : " + zipFileName);
addDirectory(directoryObject, out);
out.close();
}
private static void addDirectory(File directoryObject, ZipOutputStream out) throws IOException {
File[] files = directoryObject.listFiles();
byte[] tmpBuf = new byte[1024];
for (File file : files) {
if (file.isDirectory()) {
addDirectory(file, out);
continue;
}
FileInputStream in = new FileInputStream(file.getAbsolutePath());
System.out.println(" Adding: " + file.getAbsolutePath());
out.putNextEntry(new ZipEntry(file.getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
}
}
添加回答
举报