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條經驗 獲得超13個贊
該解決方案保留了創建的 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();
? ? ? ? }
? ? }
}
添加回答
舉報