Java压缩文件
直接上代码,不多bb
引入的包
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream
压缩文件的方法
/**
* @param root 指定要打包的路径
* @return 打好压缩包的位值
*/
public static Path compressFiles(Path root) {
// 当前文件夹的名字
final String rootName = root.toFile().getName();
// 输出的压缩包文件
final Path zipName = Paths.get(System.getProperty("user.dir") + File.separator + rootName + ".zip");
// 获取zip输出流
try (ZipOutputStream zos = new ZipOutputStream(new DataOutputStream(new FileOutputStream(zipName.toFile())))) {
// 处理传入文件夹下的所有文件
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 获取当前文件的夫目录的名字
final String parent = file.getParent().getFileName().toString();
// 压缩包中的文件名字
String zipFileName = "";
if (parent.equals(rootName)) {
// 如果是当前文件夹的文件,名字就是它自己原来的名字
zipFileName = file.toFile().getName();
} else {
// 如果是当前文件夹的文件夹下面的文件,名字就是它自己父目录的名字加上它自己的名字
zipFileName = parent + File.separator + file.toFile().getName();
}
// 把文件添加到压缩包中
zos.putNextEntry(new ZipEntry(zipFileName));
// 获取文件流
final DataInputStream zis = new DataInputStream(new FileInputStream(file.toFile()));
// 写入内容到当前文件
int len;
final byte[] buff = new byte[1024 * 10];
while ((len = zis.read(buff)) != -1) {
zos.write(buff, 0, len);
}
// 关闭当前的文件流
zis.close();
return super.visitFile(file, attrs);
}
});
} catch (IOException e) {
e.printStackTrace();
}
// 返回压缩好的文件路径
return zipName;
}
使用
public static void main(String[] args) throws IOException {
// 要压缩文件的路径
final Path root = Paths.get( System.getProperty("user.dir") + File.separator + "要压缩的文件夹");
// 压缩指定的文件到当前的文件夹下
final Path path = compressFiles(root);
System.out.println(path);
}