springboot打成jar后获取classpath下文件失败
springboot打成jar后获取classpath下文件失败
之前的方式:
//读取的关键步骤
InputStream fis = CmsApplication.class.getResourceAsStream("application.yml");
File file = ResourceUtils.getFile("classpath:application.yml");
InputStream fis = new FileInputStream(file);
未打包时可以获取到文件,打包后报错
Caused by: java.io.FileNotFoundException: class path resource [application.yml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/sunmnet/JetBrains/workspace/bigdata-parse-table/target/bigdata-parse-table-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/application.yml
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:53) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
at hello.whz.Application.lambda$lookup$0(Application.java:30) [classes!/:1.0-SNAPSHOT]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.8.RELEASE.jar!/:1.5.8.RELEASE]
... 14 common frames omitted
这是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。
因此必须使用resource.getInputStream()
解决:
private static void createFile() {
try {
File dbFile = new File("./config/application.yml");
if (!dbFile.exists()) {
ClassPathResource resource = new ClassPathResource("application.yml");
InputStream fis = resource.getInputStream();
//创建目录
File db = new File("./config/application.yml");
if (!db.exists()) {
db.getParentFile().mkdirs();
}
dbFile.createNewFile();
// FileOutputStream fos = new FileOutputStream("./repository/cms.yml");
OutputStream fos = new FileOutputStream("./config/application.yml");
List<String> lines = IOUtils.readLines(fis);
for(String line : lines){
//读取yml换行
line = line+"\r\n";
byte[] bytes = line.getBytes();
fos.write(bytes);
}
fis.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}