java 模版编程

package com.jdz.lfzadmin.utils;


import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * ━━━━━━神兽出没━━━━━━
 *    ┏┓   ┏┓
 *   ┏┛┻━━━┛┻┓
 *   ┃       ┃
 *   ┃   ━   ┃
 *   ┃ ┳┛ ┗┳   ┃
 *   ┃       ┃
 *   ┃   ┻   ┃
 *   ┃       ┃
 *   ┗━┓   ┏━┛Code is far away from bug with the animal protecting
 *     ┃   ┃    神兽保佑,代码无bug
 *     ┃   ┃
 *     ┃   ┗━━━┓
 *     ┃       ┣┓
 *     ┃       ┏┛
 *     ┗┓┓┏━┳┓┏┛
 *      ┃┫┫ ┃┫┫
 *      ┗┻┛ ┗┻┛
 * ━━━━━━永无BUG!━━━━━━
 *
 * @Description: 模版
 * @Author: 痞子
 * @Date: 2023/04/22 9:55
 */

public class TemplateUtils {


    public static void main(String[] args) throws IOException {
        creadFile();
    }
    public static void creadFile() throws IOException {
        //模版存储路径
        ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader("btl/");
        GroupTemplate groupTemplate = new GroupTemplate(classpathResourceLoader, Configuration.defaultConfiguration());

        String temName = "aaa.btl";
        Template template = groupTemplate.getTemplate(temName);

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        stringObjectHashMap.put("a","喜羊羊");
        stringObjectHashMap.put("b","懒羊羊");
//        ${b} 模版中只能使用 &{} 这种模式用来接收变量
        stringObjectHashMap.put("c","美羊羊");
        stringObjectHashMap.put("d","烤全羊");
        stringObjectHashMap.put("e","涮羊肉");
        stringObjectHashMap.put("f","我一定会回来的");

        template.binding(stringObjectHashMap);

        //这里是文件存储路径 我这里是用自己的工具类进行了校验是否存在这个路径
        String filePath = "D:/TemplateUtils";
        UnZipAndRarUtil.verifyFile(filePath);

        template.renderTo(new FileOutputStream(filePath+"/+AAAAA"+".text"));
    }
}

这里是我的工具类

 /**
     * 判断文件夹是否存在不存在创建
     *
     * @param filePath 文件将要存储的路径
     * @return 文件夹是否存在 true 为存在
     */
    public static boolean verifyFile(String filePath) {
        //    判断文件夹是否存在,不存在则创建
        File folder = new File(filePath);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
            return true;
        } else {
            return true;
        }
    }
    /**
     * 判断文件是否存在不存在创建
     *
     * @param documentPath 文件存在的路径+文件名
     * @return true 为存在
     */
    public static boolean verifyDocument(String documentPath) {
        File file = new File(documentPath);
        if (!file.exists()) {
            try {
                file.createNewFile();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        } else {
            return true;
        }

    }

    /**
     *     * 文件压缩 - 单个文件
     *
     * @param documentPath 源文件路径
     * @param zipPath 压缩包存储路径
     * @param zipEntryName 压缩包中的条目
     */
    public static void byteInputStream(String documentPath,String zipPath,String zipEntryName){
        try {
            FileInputStream fileInputStream = new FileInputStream(documentPath);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            //压缩包存储路径
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(zipPath)));
            //压缩包中的条目
            zipOutputStream.putNextEntry(new ZipEntry(zipEntryName));
            byte[] bytes = new byte[1024 * 4];
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1){
                zipOutputStream.write(bytes,0,length);
            }
            zipOutputStream.close();
            bufferedInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos        zip输出流
     * @param name       压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {

        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

    /**
     * 下载文件到浏览器
     * @param request
     * @param response
     * @param filename 要下载的文件名
     * @param file     需要下载的文件对象
     * @throws IOException
     */
    public void downFile(HttpServletRequest request, HttpServletResponse response, String filename, File file) throws IOException {
        //  文件存在才下载
        if (file.exists()) {
            OutputStream out = null;
            FileInputStream in = null;
            try {
                // 1.读取要下载的内容
                in = new FileInputStream(file);

                // 2. 告诉浏览器下载的方式以及一些设置
                // 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
                String agent = request.getHeader("user-agent");
                if (agent.contains("FireFox")) {
                    filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    filename = URLEncoder.encode(filename, "UTF-8");
                }
                // 设置下载文件的mineType,告诉浏览器下载文件类型
                String mineType = request.getServletContext().getMimeType(filename);
                response.setContentType(mineType);
                // 设置一个响应头,无论是否被浏览器解析,都下载
                response.setHeader("Content-disposition", "attachment; filename=" + filename);
                // 将要下载的文件内容通过输出流写到浏览器
                out = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            }
        }
    }

    /**
     * 筛选要复制文件 是目录直接导出目录中文件 是文件就筛选
     *
     * @param sourceDirPath 源文件路径
     * @param targetDirPath 目标存储路径 不存在会被创建
     * @throws Exception
     */
    public static void copyJars(String sourceDirPath, String targetDirPath) {
        try {

            File sourceDir = new File(sourceDirPath);
            if (!sourceDir.exists()) {
                throw new Exception("目录不存在!" + sourceDirPath);
            }
            File targetDir = new File(targetDirPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File[] subFiles = sourceDir.listFiles();
            for (File subFile : subFiles) {
                if (subFile.isDirectory()) {
                    copyJars(subFile.getAbsolutePath(), targetDirPath);
                } else {
                    String name = subFile.getName();
                    // 判断文件后缀是否为.jar
                    if (name.endsWith(".txt")) {
                        System.out.print("正在复制" + name + "...");
                        // 如果文件重名,则覆盖
                        Files.copy(Paths.get(subFile.getAbsolutePath()), Paths.get(targetDirPath + "/" + subFile.getName()),
                                new CopyOption[]{StandardCopyOption.REPLACE_EXISTING});
                        System.out.println("[√]");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值