java压缩文件
时间: 2023-07-18 22:19:05 浏览: 54
在Java中,可以使用ZipOutputStream和ZipEntry来进行文件压缩。以下是一个压缩文件的示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipCompress {
public static void main(String[] args) {
String sourcePath = "source";
String zipPath = "target.zip";
try {
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File source = new File(sourcePath);
compress(source, zos, "");
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compress(File source, ZipOutputStream zos, String name) throws IOException {
if (source.isDirectory()) {
File[] files = source.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
compress(file, zos, name + source.getName() + "/");
}
} else {
ZipEntry entry = new ZipEntry(name + source.getName() + "/");
zos.putNextEntry(entry);
zos.closeEntry();
}
} else {
FileInputStream fis = new FileInputStream(source);
ZipEntry entry = new ZipEntry(name + source.getName());
zos.putNextEntry(entry);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
}
}
```
在上面的示例中,我们使用了ZipOutputStream和ZipEntry来进行文件压缩,并通过递归的方式将目录下的所有文件都进行了压缩。压缩后的文件名为target.zip,将源文件夹source中的所有文件压缩到了该文件中。