1、springboot获取当前项目路径的地址
System.getProperty("user.dir")
2、springboot获取项目根目录classpath
//获取根目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println("path:"+path.getAbsolutePath());
//如果上传目录为/static/images/upload/,则可以如下获取:
File upload = new File(path.getAbsolutePath(),"static/images/upload/");
if(!upload.exists()) upload.mkdirs();
System.out.println("upload url:"+upload.getAbsolutePath());
//在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
//在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
#设置静态资源路径,多个以逗号分隔
spring.resources.static-locations=classpath:static/,file:static/
//相对路径映射绝对路径的方式
@Configuration
public class UploadFileConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:\\mzpt_pictures\\");
}
3、springboot 读取resources目录下文件方式
//想读取resouce/picture下的bottom.png文件。只有第二种方式才能正常工作!
//方式一
File sourceFile = ResourceUtils.getFile("classpath:picture/bottom.png"); //这种方法在linux下无法工作
//方式二
Resource resource = new ClassPathResource("picture/bottom.png");