请用 java 写几种压缩文件夹的代码. 并告诉我他们的时间耗费分别是多少
时间: 2024-02-25 12:56:54 浏览: 55
以下给出两种压缩文件夹的 Java 代码,分别使用了 ZipOutputStream 和 GZIPOutputStream 进行压缩:
1. 使用 ZipOutputStream 进行压缩:
```
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
String sourceFolder = "path/to/source/folder";
String zipFile = "path/to/output/file.zip";
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
addFolderToZip(sourceFolder, sourceFolder, zos);
zos.close();
fos.close();
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + "ms");
}
private static void addFolderToZip(String folderPath, String sourceFolder, ZipOutputStream zos) throws IOException {
File folder = new File(folderPath);
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
addFolderToZip(file.getAbsolutePath(), sourceFolder, zos);
} else {
String filePath = file.getAbsolutePath().substring(sourceFolder.length() + 1);
ZipEntry zipEntry = new ZipEntry(filePath);
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
}
}
}
```
2. 使用 GZIPOutputStream 进行压缩:
```
import java.io.*;
import java.util.zip.*;
public class GzipFolder {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
String sourceFolder = "path/to/source/folder";
String gzipFile = "path/to/output/file.gz";
FileOutputStream fos = new FileOutputStream(gzipFile);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
addFolderToGzip(sourceFolder, sourceFolder, gzos);
gzos.finish();
gzos.close();
fos.close();
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + "ms");
}
private static void addFolderToGzip(String folderPath, String sourceFolder, GZIPOutputStream gzos) throws IOException {
File folder = new File(folderPath);
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
addFolderToGzip(file.getAbsolutePath(), sourceFolder, gzos);
} else {
String filePath = file.getAbsolutePath().substring(sourceFolder.length() + 1);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
gzos.write(buffer, 0, length);
}
fis.close();
}
}
}
}
```
注意:以上代码只是示例,实际使用时需要根据具体情况进行修改。
由于压缩的文件夹大小和计算机配置等因素不同,实际的时间耗费也会有所不同,无法给出准确的时间。
阅读全文