package com.system.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 下载文件
 *
 * @author Inori
 */
public class DownloadUtil {

    public static void download(HttpServletResponse response, String data,String mac) {
        //设置响应的内容类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        response.addHeader("Content-Disposition", "attachment;filename=lic"+mac+".lqlic");

        BufferedOutputStream bufferedOutputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();

            bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
            bufferedOutputStream.write(data.getBytes(StandardCharsets.UTF_8));
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (StringUtil.isNotNull(bufferedOutputStream)) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (StringUtil.isNotNull(servletOutputStream)) {
                try {
                    servletOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
