FileUtils

文件处理工具FileUtils

 

 

/**
 * 自定义的文件工具类
 *
 * @author dw
 * @date 2021-03-12
 */
public class MyFileUtil {

    private final static Logger logger = LoggerFactory.getLogger(MyFileUtil.class);

    /**
     * 导出文件响应头设置
     *
     * @param response 响应头
     * @param fileName 导出文件名字,需要带上文件后缀
     * @throws IOException
     */
    public  void setResponseInfo(HttpServletResponse response, String fileName, byte[] file) {
        OutputStream outputStream = null;
        try {
            //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //设置Http响应头告诉浏览器下载这个附件
            response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileName, "UTF8"));
            // 暴露响应头字段 Content-Disposition 方便浏览器获取后端响应的文件名
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            outputStream = response.getOutputStream();
            outputStream.write(file);
        } catch (IOException e) {
            logger.error("导出流异常 {}", e.getMessage());
        } finally {
            if (Objects.nonNull(outputStream)) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("关闭流异常 {}", e.getMessage());
                }
            }
        }
    }

    /**
     * 创建与项目打包后,与项目同级的目录
     * @param mkDir 需要创建的文件夹
     * @return 返回创建后服务器上的路径
     */
    public static String mkDirFromRoot(String mkDir){
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!path.exists()){
                path = new File("");
            }
            File file = new File(path.getAbsolutePath(), mkDir);
            if(!file.exists()){
                //如果不存在则创建目录
                file.mkdirs();
            }
            String realPath = file + "/";
            return realPath;
        } catch (FileNotFoundException e) {
            throw new RuntimeException("获取服务器路径发生错误!");
        }
    }


}

 

posted @ 2020-10-22 09:58  邓维-java  阅读(222)  评论(0)    收藏  举报