class path resource [*.*] cannot be resolved to absolute file path because it

错误描述:

 class path resource [dataSource/dataSource.txt] cannot be resolved to absolute file path because it does not reside in the file system: 
jar:file:/app/web/ydb-drug-server/ydb-drug-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/dataSource/dataSource.txt

出现错误的原因:spring cloud 项目打成JAR以后无法读取根路径和文件。

正常通过File去获取是的时候出错,但是可以通过流的形式获取。

JAR中错误获取方式:

String url = this.getClass().getClassLoader().getResource("dataSource/dataSource.txt").getFile();
File filetest = new File(url);

正确如下:

ClassPathResource resource = new ClassPathResource("dataSource/dataSource.txt");
InputStream inputStream = resource.getInputStream();

将文件通过流的形式获取,然后将流转成需要的数据格式即可.

你可能感兴趣的:(JAVA基础)