Java获取资源路径下的文件、模板

版权声明:················································································ 爱学习的小伙伴请移步新世界:http://www.itoak.cn ················································································ https://blog.csdn.net/u012534326/article/details/85408268

工作时有个需求是需要发送html格式的邮件,这里我们不讨论发邮件的事,而是讲一讲如何从java项目的资源路径下获取自定义的资源文件或者模板。我这里是需要获取html文件的内容,并替换其中的信息,发送html格式的邮件。

HTML文件内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>Channel:%s</div>
<div>AppKey:%s</div>
<div>AppSecret:%s</div>
<div>Version:%s</div>
<br>
<div style="color:#BBBBBB;font-size:15px;">------该邮件由系统发送,请勿回复!------</div>
</body>
</html>

资源路径结构如下:

然后就是java代码了:

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author wangdl
 * @Date 2018/12/20 15:15
 * @Description 邮件模板
 */
@Component
public class EmailTemplate {

    public static String ADVANCE_TITLE = "提醒通知:接口密钥即将更新";
    public static String FORMAL_TITLE = "正式通知:接口密钥更新";
    public static String ADD_TITLE = "新增通知:新增渠道密钥已生成";
    public static String ADVANCE_CONTENT = "";
    public static String FORMAL_CONTENT = "";
    public static String ADD_CONTENT = "";

    @PostConstruct
    public void loadNotice(){
        this.load("template/advanceNotice.html", "advance");
        this.load("template/formalNotice.html", "formal");
        this.load("template/addNotice.html", "add");
    }

    /**
     * 加载模板
     * @param path
     * @param type
     */
    private void load(String path, String type){
        try {
            InputStream inputStream = new ClassPathResource(path).getInputStream();
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = inputStream.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
            if (type.equals("advance"))
                ADVANCE_CONTENT = out.toString();
            if (type.equals("formal"))
                FORMAL_CONTENT = out.toString();
            if (type.equals("add"))
                ADD_CONTENT = out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

通过上面的代码,就可以在项目启动的时候加载自定义的模板内容,我们可以通过String.format(ADD_CONTENT, arg1, arg2)这种形式去替换为指定的内容。平时的一点记录,希望可以帮到需要的人。

猜你喜欢

转载自blog.csdn.net/u012534326/article/details/85408268