ZipEntry.getCompressedSize();可以获取解压缩的大小,如下面代码所示:
```java
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile, String descDir) {
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
//解决zip文件中有中文目录或者中文文件
try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"))
) {
long readSize = 0L;
long length = zipFile.length();
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
try (
InputStream in = zip.getInputStream(entry);
//输出文件路径信息
OutputStream out = new FileOutputStream(outPath);
) {
byte[] buf1 = new byte[2048];
int len;
while (-1 != (len = in.read(buf1))) {
out.write(buf1, 0, len);
}
// 累加字节长度
readSize += entry.getCompressedSize();
log.info(readSize + "/" + length);
}
}
} catch (Exception e) {
log.error("error", e);
}
log.info("******************解压完毕********************");
}
在NIO中有获取解压大小的么,Files.size(file)只能获取文件的大小,在NIO中想获取解压进度怎么做呢
/**
* 解压缩文件工具类
* @param zipFile
* @param targetPathStr
* @throws Exception
*/
public static void unzip(String zipFile, String targetPathStr) throws Exception {
File pathFile = new File(targetPathStr);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
final Path path = Paths.get(zipFile);
final URI uri = URI.create("jar:" + path.toUri());
final Map<String, String> env = new HashMap<>();
env.put("encoding", "GBK");
FileSystem fs = FileSystems.newFileSystem(uri, env);
long total = Files.size(path);
AtomicLong read =new AtomicLong();
Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = targetPathStr + file.getName(file.getNameCount() - 1);
Path target = Paths.get(name);
//读取的文件大小
log.info(read.addAndGet(Files.size(file))+"/"+total);
Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
});
}