springboot打成jar后获取classpath下⽂件失败的解决⽅案springboot打成jar后获取classpath下⽂件
代码如下:
ClassPathResource resource = new ClassPathResource("app.keystore");
File file = File();
解决⽅式如下:
1. Spring framework
String data = "";
ClassPathResource cpr = new ClassPathResource("");
try {
byte[] bdata = InputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}
2.use a file
ClassPathResource classPathResource = new ClassPathResource("");
InputStream inputStream = InputStream();
File somethingFile = ateTempFile("test", ".txt");
try {
} finally {
IOUtils.closeQuietly(inputStream);
}
Resource resource = new ClassPathResource("data.sql");
BufferedReader reader = new BufferedReader(new InputStream()));
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 = ResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
for (int i = 0; i < resources.length; i++) {
try {
InputStream is = resources[i].getInputStream();
byte[] encoded = ByteArray(is);
String content = new String(encoded, Charset.forName("UTF-8"));
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
springboot-项⽬获取resources下⽂件碰到的问题(classPath下不到⽂件和⽂件名乱码)项⽬是spring-boot + spring-cloud 并使⽤maven 管理依赖。在springboot+maven项⽬下怎么读取resources下的⽂件实现⽂件下载?
怎么获取resources⽬录下的⽂件?(相对路径)
⽅法⼀:
File sourceFile = File("classpath:templateFile/test.xlsx"); //这种⽅法在linux下⽆法⼯作
⽅法⼆:
Resource resource = new ClassPathResource("templateFile/test.xlsx"); File sourceFile = File();
我使⽤的是第⼆种。
@PostMapping("/downloadTemplateFile")
public JSONData downloadTemplateFile(HttpServletResponse response) {
String filePath = "templateFile/test.xlsx";
Resource resource = new ClassPathResource(filePath);//⽤来读取resources下的⽂件
InputStream is = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
File file = File();
if (!ists()) {
springframework jar包下载return new JSONData(false,"模板⽂件不存在");
}
is = new FileInputStream(file);
os = OutputStream();
bis = new BufferedInputStream(is);
//设置响应头信息
response.setCharacterEncoding("UTF-8");
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = new Name().getBytes(), "utf-8");
contentDisposition.append(fileName).append("\"");
//边读边写
byte[] buffer = new byte[500];
int i;
while ((i = ad(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
return new JSONData(false,"模板⽂件不存在");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null) os.close();
if(bis != null) bis.close();
if(is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new JSONData("模板⽂件下载成功");
}
⾼⾼兴兴的启动项⽬后发现还是不到⽂件,错误⽇志:
java.io.FileNotFoundException: class path resource [templateFile/test.xlsx] cannot be resolved to URL because it does not exist
at URL(ClassPathResource.java:195)
at File(AbstractFileResolvingResource.java:129)
at com.citycloud.ller.operate.OperateBusinessUserController.downloadTemplateFile(OperateBusinessUserController.java:215)
flect.NativeMethodAccessorImpl.invoke0(Native Method)
flect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
flect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at flect.Method.invoke(Method.java:498)
at org.hod.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.hod.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.hod.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.hod.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.hod.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.hod.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at at.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.ics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158)
at org.springframework.ics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126)
at org.springframework.ics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
因为我知道Resource resource = new ClassPathResource("templateFile/test.xlsx");就是到classPath*(注意这⾥有个*)下去,然后就去项⽬本地的⽬录下classPath下是否有这个⽂件(maven的classPath在 “target\classes”⽬录下),就发现并没有这个⽂件在。
后⾯仔细想想这是Maven项⽬啊,所以就l⽂件去看看,突然想起:springboot的maven默认只会加载classPath同级⽬录下⽂件(配置那些),其他的需要配置<resources>标签:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</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”)就⾏:
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = Name();
contentDisposition.append(fileName).append("\"");
//设置⽂件名编码
String contentDispositionStr = new String().getBytes(), "iso-8859-1");
到此全部结束!
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论