public static void main(String argv[]) {
try {
String date = new java.text.SimpleDateFormat("MM-dd-yyyy")
.format(new java.util.Date());
File inFolder = new File("Output/" + date + "_4D");
File outFolder = new File("Output/" + date + "_4D" + ".zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(outFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inFolder.list();
for (int i = 0; i < files.length; i++) {
in = new BufferedInputStream(new FileInputStream(
inFolder.getPath() + "/" + files[i]), 1000);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while ((count = in.read(data, 0, 1000)) != -1) {
out.write(data, 0, count);
}
out.closeEntry();
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试压缩包含子文件夹的文件夹.尝试压缩名为10-18-2010_4D的文件夹.上述程序以以下异常结束.请告知如何解决问题.
java.io.FileNotFoundException: Output\10-18-2010_4D\4D (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at ZipFile.main(ZipFile.java:17)
Run Code Online (Sandbox Code Playgroud)
小智 26
这是创建ZIP存档的代码.创建的存档保留原始目录结构(如果有).
public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception {
if (fileToZip == null || !fileToZip.exists()) {
return;
}
String zipEntryName = fileToZip.getName();
if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) {
zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
}
if (fileToZip.isDirectory()) {
System.out.println("+" + zipEntryName);
for (File file : fileToZip.listFiles()) {
addDirToZipArchive(zos, file, zipEntryName);
}
} else {
System.out.println(" " + zipEntryName);
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(fileToZip);
zos.putNextEntry(new ZipEntry(zipEntryName));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}
Run Code Online (Sandbox Code Playgroud)
调用此方法后,请不要忘记关闭输出流.这是一个例子:
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:\\Users\\vebrpav\\archive.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
addDirToZipArchive(zos, new File("C:\\Users\\vebrpav\\Downloads\\"), null);
zos.flush();
fos.flush();
zos.close();
fos.close();
}
Run Code Online (Sandbox Code Playgroud)
只需使用这个库Zeroturnaround Zip 库
然后你将只压缩你的文件夹一行:
ZipUtil.pack(new File("D:\\sourceFolder\\"), new File("D:\\generatedZipFile.zip"));
Run Code Online (Sandbox Code Playgroud)