SpringBoot获取文件方式

SpringBoot 获取文件方式

介绍

  用于在 SpringBoot 项目中,读取项目中的文件,如 Excel 文件等。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.springframework.util.ClassUtils;

public class GetFile {

public static void main(String[] args) {
ResourceLoader resourceLoader = new DefaultResourceLoader();
InputStream inputStream = resourceLoader.getResource("classpath:dcexcel.xlsx").getInputStream();
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
log.info(path);
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("dcexcel.xlsx");
ClassPathResource resource = new ClassPathResource("dcexcel.xlsx");
InputStream inputStream = resource.getInputStream();
InputStream resourceAsStream = this.getClass().getResourceAsStream("dcexcel.xlsx");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("dcexcel.xlsx", "UTF-8"));
ServletOutputStream outputStream = response.getOutputStream();

byte[] buffer = new byte[1024];
int i = inputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = inputStream.read(buffer);
}
outputStream.close();
}

}