Java实现zip文件解压

实体类(在yml文件中配置的,不是来源于数据库,有利于后期更改和传参):

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class Parameters {
    @Value("${PublishServiceParameters.destDirPath}")
    private String zipPath;//由前端传来的zip文件同解压后文件放在了同一目录下
    @Value("${PublishServiceParameters.destDirPath}")
    private String unzipPath;
}

对应的yml配置文件:

#解压文件
PublishServiceParameters:
  #解压位置
  destDirPath: D:/

service层:

import java.io.File;

public interface ZipService {
    
    void UnZip(File dest);
}

serviceImpl层:

@Service
public class ZipServiceImpl implements ZipService {
	@Override
    public void UnZip(File dest){
    	//获取当前压缩文件
        File srcFile = dest;
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        String base = destDirPath + File.separator + System.currentTimeMillis() + File.separator + dest.getName();
        ZipFile zipFile = new ZipFile(srcFile);//创建压缩文件对象
        //开始解压
        Enumeration<?> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            // 如果是文件夹,就创建个文件夹
            if (entry.isDirectory()) {
                String dirPath = base + File.separator + entry.getName();
                new File(dirPath).mkdirs();
            } else {
                // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                File targetFile = new File(base + File.separator + entry.getName());
                // 保证这个文件的父文件夹必须要存在
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zipFile.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(targetFile);
                int len;
                //字节数组,缓存
                byte[] buf = new byte[1024 * 8];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                fos.close();
                is.close();
            }
        }
    }
}

controller层:

//使用自己的测试工具测试一下,我这里使用的是swagger
@Api(tags = {"pointcloudUpload"}, description = "自动解压发布服务")
@RestController
@RequestMapping("pointcloudUpload")
public class PublishingServiceController extends SuperController {

    @Autowired
    private ZipService zipService;

	@Autowired
    private Parameters parameters;
    
    @ApiOperation("解压文件发布项目")
    @PostMapping("/upload")
    public ApiResponses insertGisLayers(@RequestParam("file") MultipartFile file) throws Exception {
        if (!file.getOriginalFilename().toLowerCase().endsWith(".zip")) {
            throw new RuntimeException("不允许的文件类型");
        }
        String savePath = parameters.getZipPath() + File.separator + System.currentTimeMillis() + File.separator + file.getOriginalFilename();
        File dest = new File(savePath);
        dest.getParentFile().mkdirs();
        file.transferTo(dest);
        zipService.UpZip(dest);
        return success();
    }

}

如果需要查找解压后文件中的某些特定文件,可以使用递归遍历解压之后的文件,查找到自己需要的文件

	/**
     * 递归遍历文件
     *
     * @param file
     * @param lists
     */
    private void digui(File file, ArrayList<File> lists) {
        File[] files = file.listFiles();//返回某个目录下所有文件和目录的绝对路径,返回的是File数组
        if (files != null) {
            for (File file2 : files) {
                if (file2.isFile()) {
                	//查找需要的文件,加入到list集合
                    if (file2.getName().equalsIgnoreCase("tileset.json")) {
                        lists.add(file2);
                    }
                } else if (file2.isDirectory()) {
                    digui(file2, lists);
                }
            }
        }
    }

然后对ZipServiceImp进行修改,主要是调用此方法

@Service
public class ZipServiceImpl implements ZipService {
	@Override
    public void UnZip(File dest){
    	//获取当前压缩文件
        File srcFile = dest;
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        String base = destDirPath + File.separator + System.currentTimeMillis() + File.separator + dest.getName();
        ZipFile zipFile = new ZipFile(srcFile);//创建压缩文件对象
        //开始解压
        Enumeration<?> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            // 如果是文件夹,就创建个文件夹
            if (entry.isDirectory()) {
                String dirPath = base + File.separator + entry.getName();
                new File(dirPath).mkdirs();
            } else {
                // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                File targetFile = new File(base + File.separator + entry.getName());
                // 保证这个文件的父文件夹必须要存在
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zipFile.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(targetFile);
                int len;
                //字节数组,缓存
                byte[] buf = new byte[1024 * 8];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                fos.close();
                is.close();
            }
        }
        zipFile.close();//文件被占用无法删除,close可以删除
        File file = new File(base);//解压后的路径base
        //删除zip包
        try {
            new File(dest.getAbsolutePath()).delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<File> list = new ArrayList<>();
        // 获取解压目录里面的tileset.json,存到list
        digui(file, list);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值