FileUtils
下载jar中的文件
package com.meeno.chemical.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/**
* 文件工具类
*/
@Slf4j
public class FileUtils {
/**
* 下载指定目录文件
* @param res
* @param downFileName 下载文件名 xxx模板.xlsx
* @param resourcePath 下载路径 static/down/materielTemplate.xlsx
*/
public static void downloadFile(HttpServletResponse res,String downFileName,String resourcePath){
String fileName = downFileName;
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream;charset=utf-8");
try {
res.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buff = new byte[1024];
// BufferedInputStream bis = null;
InputStream bis = null;
OutputStream os = null;
try {
//第一种
//ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
//InputStream inputStream =classPathResource.getInputStream();
//第二种
//InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");
//第三种
//InputStream inputStream = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");
//第四种
//File file = ResourceUtils.getFile("classpath:excleTemplate/test.xlsx");
//InputStream inputStream = new FileInputStream(file);
//前三种方法在开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到,第四种只有开发环境 时可以读取到,生产环境读取失败。
//推测主要原因是springboot内置tomcat,打包后是一个jar包,无法直接读取jar包中的文件,读取只能通过类加载器读取。
//前三种都可以读取到其实殊途同归,直接查看底层代码都是通过类加载器读取文件流,类加载器可以读取jar包中的编译后的class文件,当然也是可以读取jar包中的excle模板了。
//String path = ResourceUtils.getURL("classpath:static/projectRes/樊登.xlsx").getPath();
//Resource resource = new ClassPathResource("static/projectRes/樊登子级用户模板.xlsx");
bis = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
//Resource resource = new ClassPathResource(resourcePath);
//File file = resource.getFile();
os = res.getOutputStream();
//bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}