欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javaweb使用freemarket 导出word ,pdf 工具类

程序员文章站 2022-07-10 18:26:58
简单记录一些技术点,不是什么难点,但用起来方便,不支持扩展后缀名.例如,可以导出doc,但不支持docx.工具类package com.yx.service.common.doc.impl;import com.aspose.words.Document;import com.aspose.words.License;import com.aspose.words.SaveFormat;import com.yx.model.hk.entity.HkWeldingProcedure;i...

简单记录一些技术点,不是什么难点,但用起来方便,不支持扩展后缀名.例如,可以导出doc,但不支持docx.

环境依赖:该依赖不好导入一般需要手动导入,给一个跟我项目配套资源链接,是我自己上传的,就在本项目中使用https://download.csdn.net/download/camel_gold/13108504

	<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker freemarker模板 -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
		</dependency>
	<!-- https://mvnrepository.com/artifact/com.aspose.words/aspose-words-jdk16 -->
		<dependency>
			<groupId>com.aspose.words</groupId>
			<artifactId>aspose-words-jdk16</artifactId>
			<version>15.8.0</version>
		</dependency>

工具类

package com.yx.service.common.doc.impl;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.yx.model.hk.entity.HkWeldingProcedure;
import com.yx.service.common.doc.DocService;
import com.yx.utils.common.FileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * created by asus on 2019/8/19.
 */
@Service
@SuppressWarnings("ALL")
class DocServiceImpl implements DocService {

    static Logger logger = LoggerFactory.getLogger(DocServiceImpl.class);
    static String tplPath = "/freemarker/template";
    /**
     * 保存模板
     */
    private static Map<String, Template> tpls = new HashMap<String, Template>();

    static {
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setDefaultEncoding("utf-8");
            configuration.setNumberFormat("0.#");
            configuration.setClassForTemplateLoading(DocServiceImpl.class, tplPath);
            List<String> files = FileUtil.getAllFiles(DocServiceImpl.class.getResource("/").getPath().replaceAll("^/", "") + tplPath);
            if (files != null) {
                for (String file : files) {
                    try {
                        Template tpl = configuration.getTemplate(file);
                        tpls.put(file, tpl);
                    } catch (TemplateNotFoundException e) {
                        logger.error("未配置模板文件:" + file);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Autowired
    HttpServletRequest req;
    @Autowired
    HttpServletResponse res;

    //获取兼容的文件名
    @Override
    public String genCompitableName(String fileName, String suffix) {
        if (isIE()) {
            try {
                fileName = java.net.URLEncoder.encode(fileName + suffix, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return fileName + suffix;
    }

    //下载失败,消息提示
    @Override
    public void failDown(String msg) {
        OutputStreamWriter writer = null;
        try {
            res.reset();
            writer = new OutputStreamWriter(res.getOutputStream(), StandardCharsets.UTF_8);
            String data = "<script language='javascript'>alert(\"" + msg + "\");window.history.back();</script>";
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
    *@author 小王
    *@date 2020/10/19 23:16
    ** @param map
     * @param hkWeldingProcedure
     * @param tplFile
    *@return java.io.File
    *@Description:  保存模板文件到本地
    **/
    @Override
    public File save2Local(Map<String, Object> map, String filePath, String tplFile) {
            File file=null,pdfFile=null;
            if(map.size()>0){
                pdfFile=new File(filePath+ ".pdf");
                if(!pdfFile.getParentFile().exists()){
                    //先得到文件的上级目录,并创建上级目录
                    pdfFile.getParentFile().mkdirs();
                }
                if(pdfFile.exists()){
                    pdfFile.delete();
                }
                if (tplFile != null) {
                    Template tpl = tpls.get(tplFile);
                    if (tpl != null) {
                        FileOutputStream fileOs = null;
                        FileInputStream fileIs = null;
                        FileOutputStream pdfOs = null;
                        try {
                            if (tpl.toString().contains("Word.Document")) {
                                file = new File(filePath + ".doc");
                            } else {
                                throw new RuntimeException("请设置word模板");
                            }
                            fileOs = new FileOutputStream(file);
                            Writer w = new OutputStreamWriter(fileOs, StandardCharsets.UTF_8);
                            //freemaker渲染保存
                            tpl.process(map, w);
                            if (getLicense()) {
                                fileIs = new FileInputStream(file);
                                Document doc = new Document(fileIs);
                                //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                                pdfOs = new FileOutputStream(pdfFile);
                                doc.save(pdfOs, SaveFormat.PDF);
                            } else {
                                throw new RuntimeException("转换证书异常");
                            }
                        } catch (TemplateException e) {
                            e.printStackTrace();
                            throw new RuntimeException("模板处理异常");
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("转换处理异常");
                        } finally {
                            try {
                                if (fileOs != null) {
                                    fileOs.close();
                                }
                                if (fileIs != null) {
                                    fileIs.close();
                                }
                                if (pdfOs != null) {
                                    pdfOs.close();
                                }
                                if (file != null) {
                                    boolean delete = file.delete();
                                }
                            } catch (IOException e) {
                                throw new RuntimeException("IO异常!");
                            }
                        }
                    }else {
                        throw new RuntimeException("模板文件未配置");
                    }
                } else {
                    throw new RuntimeException("模板文件参数空");
                }
            }
            return pdfFile;

    }

    //纯流操作/

    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * @param fileName 文档名
     * @return
     */
    @Override
    public void genDocEx(Map<String, Object> dataMap, String tplFile, String fileName) {
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                if (tpl.toString().contains("Word.Document")) {//文档
                    fileName = genCompitableName(fileName, ".doc");
                } else {//表格
                    fileName = genCompitableName(fileName, ".xls");
                }
                res.reset();
                res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
                res.setContentType("application/octet-stream");
                try (ServletOutputStream os = res.getOutputStream()) {
                    Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                    tpl.process(dataMap, w);
                } catch (TemplateException | IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("模板处理异常");
                }
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }

    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * @param fileName 文档名
     * @return
     */
    @Override
    public void genPdfEx(Map<String, Object> dataMap, String tplFile, String fileName) {
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                fileName = genCompitableName(fileName, ".pdf");
                res.reset();
                res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
//                res.addHeader("Content-Length", "" + file.length);
                res.setContentType("application/octet-stream");
                ByteArrayOutputStream os = null;
                ByteArrayInputStream is = null;
                try {
                    os = new ByteArrayOutputStream();
                    Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                    tpl.process(dataMap, w);
                    is = new ByteArrayInputStream(os.toByteArray());
                    if (getLicense()) {
                        Document doc = new Document(is);
                        doc.save(res.getOutputStream(), SaveFormat.PDF);
                    } else {
                        throw new RuntimeException("PDF证书异常");
                    }
                } catch (TemplateException | IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("文档模板异常");
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("文档转换异常");
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                        if (is != null) {
                            is.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }

    /**
     * 打包下载
     *
     * @param dataMaps 数据maps
     * @param tplFile  模板
     * @param fileName zip名称
     * @param type     类型
     * @throws IOException
     */
    @Override
    public void genZip(List<Map<String, Object>> dataMaps, String tplFile, String fileName, int type) throws IOException {
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                fileName = genCompitableName(fileName, ".zip");
                res.reset();
                res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
                res.setContentType("application/octet-stream");
                //获取zip输出流
                ZipOutputStream out = new ZipOutputStream(res.getOutputStream());
                byte[] buffer = new byte[1024];
                for (Map<String, Object> dataMap : dataMaps) {
                    ByteArrayOutputStream os = null;
                    ByteArrayInputStream is = null;
                    try {
                        os = new ByteArrayOutputStream();
                        Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                        tpl.process(dataMap, w);

                        //获取doc输入流
                        is = new ByteArrayInputStream(os.toByteArray());
                        if (type == 2) {
                            if (getLicense()) {
                                Document doc = new Document(is);
                                os.close();
                                os = new ByteArrayOutputStream();
                                doc.save(os, SaveFormat.PDF);
                                //获取pdf输入流
                                is.close();
                                is = new ByteArrayInputStream(os.toByteArray());
                            } else {
                                throw new RuntimeException("证书异常");
                            }
                        }

                        Object name = dataMap.get("fileName");
                        if (!(name instanceof String)) {
                            throw new RuntimeException("获取文件名失败");
                        }
                        //加入zip
                        out.putNextEntry(new ZipEntry(genCompitableName(String.valueOf(name), getSuffix(type))));
                        int len;
                        while ((len = is.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        out.closeEntry();
                    } catch (TemplateException | IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException("模板处理异常");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (os != null) {
                                os.close();
                            }
                            if (is != null) {
                                is.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }

    /**
     * 根据类型获取后缀
     *
     * @param type
     * @return
     */
    String getSuffix(int type) {
        switch (type) {
            case 0:
                return ".doc";
            case 1:
                return ".xls";
            case 2:
                return ".pdf";
        }
        return ".unknow";
    }
    //纯流操作/

    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * @param fileName 文档名
     * @return
     */
    @Override
    public File genDoc(Map<String, Object> dataMap, String tplFile, String fileName) throws IOException, TemplateException {
        File f;
        if (isIE()) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                if (tpl.toString().contains("Word.Document")) {
                    f = new File(fileName + ".doc");
                } else {
                    f = new File(fileName + ".xls");
                }
                FileOutputStream fileOs = null;
                try {
                    fileOs = new FileOutputStream(f);
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    Writer w = new OutputStreamWriter(fileOs, StandardCharsets.UTF_8);
                    tpl.process(dataMap, w);
                } catch (TemplateException e) {
                    e.printStackTrace();
                    throw new RuntimeException("模板处理异常");
                } finally {
                    if (fileOs != null) {
                        fileOs.close();
                    }
                }
                return f;
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }


    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * @param fileName 文档名
     * @return
     */
    @Override
    public File genPdf(Map<String, Object> dataMap, String tplFile, String fileName) throws IOException {
        File file = null, pdfFile = null;
        if (isIE()) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                FileOutputStream fileOs = null;
                FileInputStream fileIs = null;
                FileOutputStream pdfOs = null;
                try {
                    if (tpl.toString().contains("Word.Document")) {
                        file = new File(fileName + ".doc");
                    } else {
                        throw new RuntimeException("请设置word模板");
                    }
                    fileOs = new FileOutputStream(file);
                    Writer w = new OutputStreamWriter(fileOs, StandardCharsets.UTF_8);
                    //freemaker渲染保存
                    tpl.process(dataMap, w);

                    //pdf 文件
                    pdfFile = new File(fileName + ".pdf");
                    if (getLicense()) {
                        fileIs = new FileInputStream(file);
                        Document doc = new Document(fileIs);
                        //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                        pdfOs = new FileOutputStream(pdfFile);
                        doc.save(pdfOs, SaveFormat.PDF);
                    } else {
                        throw new RuntimeException("转换证书异常");
                    }
                } catch (TemplateException e) {
                    e.printStackTrace();
                    throw new RuntimeException("模板处理异常");
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("转换处理异常");
                } finally {
                    if (fileOs != null) {
                        fileOs.close();
                    }
                    if (fileIs != null) {
                        fileIs.close();
                    }
                    if (pdfOs != null) {
                        pdfOs.close();
                    }
                    if (file != null) {
                        boolean delete = file.delete();
                    }
                }
                return pdfFile;
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }

    /**
     * word 转pdf License
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            String s = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                    "<License>\n" +
                    "    <Data>\n" +
                    "        <Products>\n" +
                    "            <Product>Aspose.Total for Java</Product>\n" +
                    "            <Product>Aspose.Words for Java</Product>\n" +
                    "        </Products>\n" +
                    "        <EditionType>Enterprise</EditionType>\n" +
                    "        <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                    "        <LicenseExpiry>20991231</LicenseExpiry>\n" +
                    "        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                    "    </Data>\n" +
                    "    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                    "</License>";
            ByteArrayInputStream lis = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
            License aposeLic = new License();
            aposeLic.setLicense(lis);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private boolean isIE() {
        if (req != null) {
            String userAgent = req.getHeader("User-Agent");
            return userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge");
        }
        return false;
    }

}

常用相关工具类

文件下载:

package com.yx.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * created by zm on 2018/8/20.
 */
public class FileUtils {

    // 图片转化成base64字符串
    public static String file2Base64(File file) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    // base64 串转图片 并存储
    public static boolean generateImage(String filePath, String fileBase64Str) { // 对字节数组字符串进行Base64解码并生成图片
        if (fileBase64Str == null) // 图像数据为空
            return false;
        OutputStream out = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(fileBase64Str);

            File destFile = new File(filePath);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            for (int i = 0, lens = bytes.length; i < lens; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            out = new FileOutputStream(destFile);
            out.write(bytes);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * base64 串转 inputstream
     *
     * @param fileStrBase64
     * @return
     */
    public static InputStream generateInputStream(String fileStrBase64) {
        if (fileStrBase64 == null) // 图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(fileStrBase64);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            return null;
        }
    }

    纯流操作
    //浏览器端下载
    public static void downFile(byte[] file, String fileName, HttpServletResponse response) {
        InputStream in = null;
        OutputStream out = null;
        try {
            // 以流的形式下载文件。
            in = new ByteArrayInputStream(file);
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            // 清空response
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length);
            response.setContentType("application/octet-stream");
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(buffer);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("导出失败", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("导出失败", e);
            }
        }
    }
    纯流操作

    //浏览器端下载
    public static void downFile(File file, HttpServletResponse response) {
        InputStream in = null;
        OutputStream out = null;
        try {
            // 以流的形式下载文件。
            in = new FileInputStream(file);
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            // 清空response
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(buffer);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("导出失败", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                if (file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                throw new RuntimeException("导出失败", e);
            }
        }
    }


    //下载失败
    public static void failDown(HttpServletResponse response, String msg) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = "<script language='javascript'>alert(\"" + msg + "\");window.history.back();</script>";
        try {
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param response
     * @return void
     * @author 小王
     * @date 2020/10/11 19:46
     * * @param files
     * @Description: zip导出
     **/
    public static void downZip(List<File> files, HttpServletResponse response, String fileName) {
        ZipOutputStream out = null;
        byte[] buffer = new byte[1024];
        List<String> list = new ArrayList<>();
        for (File file : files) {
            try {
                list.add(file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            fileName += ".zip";
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
            response.setContentType("application/octet-stream");
            //获取zip输出流
            out = new ZipOutputStream(response.getOutputStream());
            //添加压缩文件
            if (files != null && files.size() > 0) {
                for (File file : files) {
                    FileInputStream fis = new FileInputStream(file);
                    out.putNextEntry(new ZipEntry(file.getName()));
                    int fileLen;
                    while ((fileLen = fis.read(buffer)) > 0) {
                        out.write(buffer, 0, fileLen);
                    }
                    out.closeEntry();
                    fis.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (out != null) {
                    out.close();
                }
            /*    if (files != null) {
                    for (File file : files) {
                        file.delete();
                    }
                }*/
                if (list != null) {
                delTemporaryFile(list);
            }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    /**
     * @return void
     * @author 小王
     * @date 2020/10/11 21:57
     * * @param pathList
     * @Description: 根据文件路径删除文件
     **/
    public static void delTemporaryFile(List<String> pathList) {
        if (pathList.size() > 0) {
            for (String string : pathList) {
                File file = new File(string);
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {

        System.out.println(System.getProperty("java.class.path"));
    }
}

图片解析:

package com.yx.utils.common;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * created by zm on 2018/7/12.
 */
public class FileUtil {
    /**
     * MultipartFile 转文件
     *
     * @param mulFile
     * @return
     */
    public static File multifileToFile(MultipartFile mulFile) {
        if (mulFile != null) {
            File file = new File(mulFile.getOriginalFilename());
            try {
                FileUtils.copyToFile(mulFile.getInputStream(), file);
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取某个文件夹下的所有文件
     *
     * @param path 文件夹的路径
     * @return
     */
    public static List<String> getAllFiles(String path) {
        ArrayList<String> files = new ArrayList<>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        if (tempList != null) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    files.add(tempList[i].getName());
                }
            }
        }
        return files;
    }

    /**
     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
     *
     * @param sourceFilePath :待压缩的文件路径
     * @param zipFilePath    :压缩后存放路径
     * @param fileName       :压缩后文件的名称
     * @return
     */
    public static File file2Zip(String sourceFilePath, String zipFilePath, String fileName) {
        File zipFile = null;//返回压缩后文件

        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        if (sourceFile.exists()) {
            try {
                String filepath = zipFilePath + "/" + fileName + ".zip";
                zipFile = new File(filepath);
                if (zipFile.exists()) {//存在,删除旧的
                    FileUtils.deleteQuietly(zipFile);
                    zipFile = new File(filepath);
                }
                File[] sourceFiles = sourceFile.listFiles();
                if (null != sourceFiles && sourceFiles.length > 0) {
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024 * 10];
                    for (File file : sourceFiles) {
                        // 创建ZIP实体,并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);
                        // 读取待压缩的文件并写进压缩包里
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis, 1024 * 10);
                        int read;
                        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                            zos.write(bufs, 0, read);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return zipFile;
    }

    /**
     * 根据byte数组,生成文件
     *
     * @param bytes    文件数组
     * @param filePath 文件存放路径
     * @param fileName 文件名称
     */
    public static void byte2File(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {// 判断文件目录是否存在
                boolean mkdirs = dir.mkdirs();
            }
            file = new File(filePath + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            System.out.println(e.getMessage() + "========" + file);
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得指定文件的byte数组
     *
     * @param filePath 文件绝对路径
     * @return
     */
    public static byte[] file2Byte(String filePath) {
        ByteArrayOutputStream bos = null;
        BufferedInputStream in = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("file not exists");
            }
            bos = new ByteArrayOutputStream((int) file.length());
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    // 字符串转换成数组
    public static byte[] toByteArray(String hexString) {
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {// 因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    /**
     * 字符串转换成字节流并输出
     */
    public static void imageFile(HttpServletResponse response, byte[] bytes, String filePath, String fileName) {

        // byte[] bytes = CommonUtil.toByteArray(xx);
//		byte[] bytes = xx.getBytes();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.addHeader("Content-Type", "image/jpeg");
            os.write(bytes);
            os.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            BufferedImage bi1 = ImageIO.read(bais);
            File w2 = new File("E://demo//demo.png");//可以是jpg,png,gif格式
            ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String saveFile(MultipartFile mulFile, String path) {
        if (mulFile != null) {
            File file = new File(path + File.separator + mulFile.getOriginalFilename());
            try {
                FileUtils.copyToFile(mulFile.getInputStream(), file);
                return file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String file2Base64(File file) {
        if (file == null) {
            return null;
        }
        String base64 = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] buff = new byte[fin.available()];
            fin.read(buff);
            base64 = Base64.encode(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    public static File base64ToFile(String base64) {
        if (base64 == null || "".equals(base64)) {
            return null;
        }
        byte[] buff = Base64.decode(base64);
        File file = null;
        FileOutputStream fout = null;
        try {
            file = File.createTempFile("tmp", null);
            fout = new FileOutputStream(file);
            fout.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 网络资源转base64
     *
     * @param netUrl
     * @return
     */
    public static String netToBase64(String netUrl) {
        String base64 = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAKAQMAAACOm+ylAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAANQTFRFAAAAp3o92gAAAAF0Uk5TAEDm2GYAAAAMSURBVHicY2AgDgAAACgAATVUcoQAAAAASUVORK5CYII=";
        if (netUrl != null) {
            URL url = null;
            try {
                url = new URL(netUrl);
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                byte[] context = output.toByteArray();
                base64 = Base64.encode(context);
                dataInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    private static final String ENCODE = "UTF-8";
    private static final int PIC_LINE = 76;

    //文档图片base64加换行
    private static String getDocBase64(String pic) {
        String pic_n = "";
        if (pic != null) {
            while (pic.length() >= PIC_LINE) {
                String lineStr = pic.substring(0, PIC_LINE);
                pic = pic.substring(PIC_LINE);
                if (pic_n.length() == 0) {
                    pic_n = lineStr;
                    continue;
                }
                pic_n = pic_n + "\r\n" + lineStr;
            }
            if (pic_n.length() == 0) {
                pic_n = pic;
            } else {
                if (pic.length() > 0) {
                    pic_n = pic_n + "\r\n" + pic;
                }
            }
        }
        return pic_n;
    }

    public static String net2DocBase64(String url) {
        String pic64 = netToBase64(url);
        if (pic64 != null) {
            String docBase64 = getDocBase64(pic64);
            if (docBase64 != null) {
                return docBase64;
            }
        }
        return "";
    }

    //链接url下载图片
    private static void downloadPicture(String netUrl) {
        URL url = null;
        int imageNumber = 0;

        try {
            url = new URL(netUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            String imageName = "F:/test.jpg";

            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context = output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        String url = "D:\\图片\\img\\man09.jpg";
//        downloadPicture(url);

//        String pic64 = netToBase64(url);
//        if (pic64 != null) {
            System.err.println(pic64);
//            String docBase64 = getDocBase64(pic64);
//            if (docBase64 != null) {
//                System.err.println(docBase64);
//            }
//        }
        //System.err.println(getImageBase(url));

    }

    public static String getFileSuffix(String url) {
        if (url != null && url.length() > 0) {
            String[] split = url.split("\\.");
            if (split.length > 1) {
                return split[split.length - 1];
            }
        }
        return "unknow";
    }


}

解析模板图片后缀名(基本上覆盖全网):这个很重要,不然导出模板图片将无法显示

package com.yx.utils.common;

/**
 * @ProjectName: sfhk
 * @Package: com.yx.utils.common
 * @ClassName: ImgUnit
 * @Author: 老王
 * @Date: 2020/10/8 9:30
 * @Description: 图片工具类
 */
public class ImgUnit {

    /**
     * @return java.lang.String
     * @author 小王
     * @date 2020/10/8 9:32
     * * @param imgName
     * @Description: 根据图片后缀判断图片MIME类型, 参考地址:https://blog.csdn.net/focusforce/article/details/6301954
     **/
    public static String getImgType(String imgName) {
        String[] split = imgName.split("\\.");
        String suffix = split[split.length - 1];
        String typeString = "";
        switch (suffix) {
            case "bmp":
                typeString = "image/bmp";
                break;

            case "tiff":
                typeString = "image/tiff";
                break;

            case "tif":
                typeString = "image/tiff";
                break;

            case "png":
                typeString = "image/png";
                break;

            case "gif":
                typeString = "image/gif";
                break;

            case "jpeg":
                typeString = "image/jpeg";
                break;

            case "jpg":
                typeString = "image/jpeg";
                break;

            case "xpm":
                typeString = "image/x-xpm";
                break;

            case "pcx":
                typeString = "image/pcx";
                break;

            case "svg":
                typeString = "image/svg+xml";
                break;

            case "wmf":
                typeString = "image/x-wmf";
                break;

            case "dxf":
                typeString = "image/vnd.dxf";
                break;

            case "cgm":
                typeString = "image/cgm";
                break;

            case "emf":
                typeString = "image/x-emf";
                break;

            case "ico":
                typeString = "image/x-icon";
                break;
        }
        return typeString;
    }

}

 

本文地址:https://blog.csdn.net/camel_gold/article/details/109643639

相关标签: java