因为是工作中遇到的问题,所以在自己电脑写了个简单例子还原记录一下
只在本地能load,不能在环境上load的代码写法:
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.IOException;
public static void main(String[] args) {
try {
ClassPathResource classPathResource = new ClassPathResource("config/account_status.yml");//该路径基于src/resources
File file = classPathResource.getFile();
System.out.println(file.getName());
} catch (IOException e) {
System.out.println("file can't find");
e.printStackTrace();
}
}
问题出现原因:这是因为打包后Spring试图访问文件系统路径,但是无法访问jar中的路径
解决方法,将以上代码改成如下
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class TestFileLoadIssue {
public static void main(String[] args) {
try {
ClassPathResource classPathResource = new ClassPathResource("config/account_status.yml");
InputStream inputStream = classPathResource.getInputStream();
File file = new File(classPathResource.getFilename());
FileUtils.copyInputStreamToFile(inputStream,file);
System.out.println(file.getName());
} catch (IOException e) {
System.out.println("file can't find");
e.printStackTrace();
}
}
}
can check here:https://smarterco.de/java-load-file-from-classpath-in-spring-boot/