Java Code Examples for cn.hutool.core.util.ZipUtil#zip()

The following examples show how to use cn.hutool.core.util.ZipUtil#zip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份数据库
 *
 * @return 重定向到/admin/backup
 */
public JsonResult backupDatabase() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/databases/");
        }
        final String srcPath = System.getProperties().getProperty("user.home") + "/halo/";
        final String distName = "databases_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //压缩文件
        ZipUtil.zip(srcPath + "halo.mv.db", System.getProperties().getProperty("user.home") + "/halo/backup/databases/" + distName + ".zip");
        log.info("Current time: {}, database backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup database failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 2
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份文章,导出markdown文件
 *
 * @return JsonResult
 */
public JsonResult backupPosts() {
    List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
        }
        //打包好的文件名
        String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
        for (Post post : posts) {
            HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
        }
        //打包导出好的文章
        ZipUtil.zip(srcPath, srcPath + ".zip");
        FileUtil.del(srcPath);
        log.info("Current time: {}, performed an article backup.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup article failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 3
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @return JsonResult
 */
public JsonResult backupResources() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
        }
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        String srcPath = path.getAbsolutePath();
        String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //执行打包
        ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
        log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup resource file failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 4
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份数据库
 *
 * @return 重定向到/admin/backup
 */
public JsonResult backupDatabase() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/databases/");
        }
        String srcPath = System.getProperties().getProperty("user.home") + "/halo/";
        String distName = "databases_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //压缩文件
        ZipUtil.zip(srcPath + "halo.mv.db", System.getProperties().getProperty("user.home") + "/halo/backup/databases/" + distName + ".zip");
        log.info("Current time: {}, database backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup database failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 5
Source File: ApiController.java    From littleca with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "downCertZip", method = RequestMethod.GET)
public void downCertZip(String serialNumber, Integer catype, HttpServletResponse resp, HttpServletRequest req) throws SerialException {
    try {
        CAConstant.KeyType keyType = CAConstant.KeyType.forValue(catype);
        CaConfig caConfig = appConfig.getByKeyType(catype);
        String certDir = caConfig.getClientCertBasePath() + "/" + serialNumber;
        String destPath = caConfig.getClientCertBasePath() + "/" + UUID.randomUUID().toString() + ".zip";
        String readmeDoc = certDir + "/readme.txt";
        String readmeTxt = "证书类型为["+keyType.name+"]p12 alias:taoyuanx-client\r\n p12 密码:123456";
        FileUtils.writeStringToFile(new File(readmeDoc), readmeTxt, "UTF-8");
        ZipUtil.zip(certDir, destPath);
        // 下载
        File destZipFile = new File(destPath);
        resp.setContentType(req.getServletContext().getMimeType(destZipFile.getName()));
        resp.setHeader("Content-type", "application/octet-stream");
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(keyType.name+"_cert.zip","UTF-8"));
        resp.getOutputStream().write(FileUtils.readFileToByteArray(destZipFile));

    } catch (Exception e) {
        throw new SerialException("下载失败");
    }
}
 
Example 6
Source File: ApiController.java    From littleca with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "downCertZip", method = RequestMethod.GET)
public void downCertZip(String serialNumber, String password, HttpServletResponse resp, HttpServletRequest req) throws SerialException {
    try {
        File zipFile = new File(appConfig.getCertBaseDir(), Math.abs(HashUtil.bkdrHash(serialNumber)) + "_cert.zip");
        String destPath = zipFile.getAbsolutePath();
        if (!zipFile.exists()) {
            String certDir = appConfig.getCertBaseDir() + File.separator + serialNumber;
            String readmeDoc = certDir + File.separator + "readme.txt";
            String readmeTxt = "p12 alias:lient\r\n p12 密码:" + password;
            FileUtils.writeStringToFile(new File(readmeDoc), readmeTxt, "UTF-8");
            ZipUtil.zip(certDir, destPath);
        }
        // 下载
        resp.setContentType(req.getServletContext().getMimeType(zipFile.getName()));
        resp.setHeader("Content-type", "application/octet-stream");
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(serialNumber + "_cert.zip", "UTF-8"));
        resp.getOutputStream().write(FileUtils.readFileToByteArray(zipFile));
    } catch (Exception e) {
        LOG.error("下载异常", e);
        throw new SerialException("下载失败");
    }
}
 
Example 7
Source File: VelocityKit.java    From kvf-admin with MIT License 6 votes vote down vote up
/**
 * 所有模板统一生成
 * @param config 代码生成配置数据
 */
public static void allToFile(GenConfigVO config) {
    VelocityContext ctx = VelocityKit.getContext();
    ctx.put("config", config);
    ctx.put("pack", new ConfigConstant.PackageConfig());
    ctx.put("createTime", DateUtil.now());
    ctx.put("author", ConfigConstant.AUTHOR);
    for (TemplateTypeEnum typeEnum : TemplateTypeEnum.values()) {
        if ("TABLE".equals(typeEnum.getType()) || "TREE_GRID".equals(typeEnum.getType())) {
            if (config.getTableType().equalsIgnoreCase(typeEnum.getType())) {
                VelocityKit.toFile(typeEnum.getName(), ctx,
                        AuxiliaryKit.getGenerateCodePath(typeEnum, config.getModuleName(), config.getFunName()));
            }
        } else {
            VelocityKit.toFile(typeEnum.getName(), ctx,
                    AuxiliaryKit.getGenerateCodePath(typeEnum, config.getModuleName(), config.getFunName()));
        }
    }

    // 所有代码文件打包zip压缩包
    final String srcPath = ConfigConstant.CODE_GEN_PATH + "/" + ConfigConstant.CODE_FOLDER_NAME;
    ZipUtil.zip(srcPath, ConfigConstant.CODE_GEN_PATH + "/" + ConfigConstant.CODE_ZIP_FILENAME);
}
 
Example 8
Source File: BuildUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 如果为文件夹自动打包为zip ,反之返回null
 *
 * @param file file
 * @return 压缩包文件
 */
public static File isDirPackage(File file) {
    if (file.isFile()) {
        return null;
    }
    String name = FileUtil.getName(file);
    if (StrUtil.isEmpty(name)) {
        name = "result";
    }
    File zipFile = FileUtil.file(file.getParentFile().getParentFile(), name + ".zip");
    if (!zipFile.exists()) {
        // 不存在则打包
        ZipUtil.zip(file.getAbsolutePath(), zipFile.getAbsolutePath());
    }
    return zipFile;
}
 
Example 9
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份文章,导出markdown文件
 *
 * @return JsonResult
 */
public JsonResult backupPosts() {
    final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
        }
        //打包好的文件名
        final String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        final String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
        for (Post post : posts) {
            HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
        }
        //打包导出好的文章
        ZipUtil.zip(srcPath, srcPath + ".zip");
        FileUtil.del(srcPath);
        log.info("Current time: {}, performed an article backup.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup article failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 10
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @return JsonResult
 */
public JsonResult backupResources() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
        }
        final File path = new File(ResourceUtils.getURL("classpath:").getPath());
        final String srcPath = path.getAbsolutePath();
        final String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //执行打包
        ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
        log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup resource file failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example 11
Source File: LogController.java    From zfile with MIT License 5 votes vote down vote up
/**
 * 系统日志下载
 */
@GetMapping("/log")
public ResponseEntity<Object> downloadLog(HttpServletResponse response) {
    if (log.isDebugEnabled()) {
        log.debug("下载诊断日志");
    }
    String userHome = System.getProperty("user.home");
    File fileZip = ZipUtil.zip(userHome + "/.zfile/logs");
    String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
    return FileUtil.export(fileZip, "ZFile 诊断日志 - " + currentDate + ".zip");
}
 
Example 12
Source File: GeneratorServiceImpl.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnConfig> columns, HttpServletRequest request, HttpServletResponse response) {
    if(genConfig.getId() == null){
        throw new BadRequestException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath()  + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtil.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new BadRequestException("打包失败");
    }
}
 
Example 13
Source File: FileManagerServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException {
    File zip = ZipUtil.zip(new File(ValueConsts.USER_DESKTOP + File.separator + destFile), ValueConsts.FALSE,
            FileExecutor.getFiles(items));
    if (zip.exists()) {
        response.getOutputStream().write(FileExecutor.readFileToByteArray(zip));
        FileExecutor.deleteFile(zip);
    }
}
 
Example 14
Source File: FileManagerServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public JSONObject compress(JSONObject object) {
    JSONArray array = object.getJSONArray("items");
    File[] files = new File[array.size()];
    int i = 0;
    for (Object file : array) {
        files[i++] = new File(file.toString());
    }
    String dest = object.getString("destination");
    String name = object.getString("compressedFilename");
    File zip = ZipUtil.zip(new File(dest + File.separator + name), ValueConsts.FALSE, files);
    return getBasicResponse(zip.exists());
}
 
Example 15
Source File: CertificateController.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 导出证书
 *
 * @param id 项目id
 * @return 结果
 */
@RequestMapping(value = "/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String export(String id) {
    CertModel item = certService.getItem(id);
    if (null == item) {
        return JsonMessage.getString(400, "导出失败");
    }
    String parent = FileUtil.file(item.getCert()).getParent();
    File zip = ZipUtil.zip(parent);
    ServletUtil.write(getResponse(), zip);
    FileUtil.del(zip);
    return JsonMessage.getString(400, "导出成功");
}
 
Example 16
Source File: GeneratorServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) {
    if (genConfig.getId() == null) {
        throw new BadRequestException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath() + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtil.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new BadRequestException("打包失败");
    }
}
 
Example 17
Source File: GeneratorServiceImpl.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) {
    if (genConfig.getId() == null) {
        throw new SkException("请先配置生成器");
    }
    try {
        File file = new File(GenUtil.download(columns, genConfig));
        String zipPath = file.getPath() + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtils.downloadFile(request, response, new File(zipPath), true);
    } catch (IOException e) {
        throw new SkException("打包失败");
    }
}