springboot项目打包之后,将所有依赖都打入jar包,同时也将系统中要使用的一些资源文件也会打进来,之后运行这个jar包,里面包含的资源文件不能再像文件系统那样直接在classpath下就可以使用了。
如下所示,这段代码在idea中运行,可以按照预期,正确访问到资源文件hello.txt。
package com.xxx.springresourcedemo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.InputStream;
@SpringBootApplication
public class SpringresourcedemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringresourcedemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
try {
String path = new ClassPathResource("hello.txt").getURL().getPath();
File file = new File(path);
System.out.println(fil