springboot打成jar后获取classpath下文件
代码如下:
ClassPathResource resource = new ClassPathResource("app.keystore");
File file = resource.getFile();
FileUtils.readLines(file).forEach(System.out::println);
解决方式如下:
1. Spring framework
String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}
2.use a file
ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
Resource resource = new ClassPathResource("data.sql");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
reader.lines().forEach(System.out::println);
String content = new ClassPathResourceReader("data.sql").getContent();
@Value("${resourceLoader.file.location}")
@Setter
private String location;
private final ResourceLoader resourceLoader;
public void readallfilesfromresources() {
Resource[] resources;
try {
resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "*.properties</include>
<include>***.properties</include>
<include>***.yml</include>
<include>**/Dockerfile</include>
<include>**/*.xlsx</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
</resources>
</build>
重新启动,再到classPath下看,发现有了这个文件了,同时也能获取了。如果文件名为中文的话就会出现乱码的情况。
怎么解决文件名中文乱码?
Access-Control-Allow-Origin →*
Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →accessToken,Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
Access-Control-Allow-Methods →POST,GET,PUT,PATCH,DELETE,OPTIONS,HEAD
Access-Control-Max-Age →360
Content-disposition →attachment; filename="????????-??????????.xlsx"
Content-Type →application/octet-stream;charset=UTF-8
Transfer-Encoding →chunked
Date →Fri, 19 Apr 2019 06:47:34 GMT
上面是使用postman测试中文乱码response响应头相关信息。
后面怎么改都乱码,然后我就试着到浏览器中请求试试,结果发现只是postman的原因,只要文件名编码跟返回内容编码一致("Content-disposition"和“ContentType”)就行:
this.response.setContentType("application/octet-stream; charset=iso-8859-1");
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = file.getName();
contentDisposition.append(fileName).append("\"");
//设置文件名编码
String contentDispositionStr = new String(contentDisposition.toString().getBytes(), "iso-8859-1");
this.response.setHeader("Content-disposition", contentDispositionStr);
到此全部结束!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。