赞
踩
代码:
- String path = "cerm/CA_CA_0_usr_0.der";
- File file = new DefaultResourceLoader().getResource(path).getFile();
- byte[] bytes = FileUtils.readFileToByteArray(file);
- System.out.println(Base64.getEncoder().encodeToString(bytes));
异常:
cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/opt/d_g.war!/WEB-INF/classes!/cerm/CA_CA_0_usr_0.der
使用idea测试时,未打包时可以获取到文件,打包后报错。
解决:
- String path = "cerm/CA_CA_0_usr_0.der";
- InputStream inputStream = new DefaultResourceLoader().getResource(path).getInputStream();
- //InputStream转为byte[]
- byte[] bytes = inputStream2Bytes(inputStream);
- System.out.println(Base64.getEncoder().encodeToString(bytes));
说明:
这是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。因此必须使用getInputStream()。
并且使用
ClassPathResource亦同理。
详情请参考:
Java: Load file from classpath in Spring Boot - smarterco.de
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。