1、测试文件具体位置
![在这里插入图片描述](https://img-blog.csdnimg.cn/96da072145fb43b5a4213c2defc2cf17.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1ZjYXRyb3k=,size_16,color_FFFFFF,t_70#pic_center)
2、方式一:项目内路径
使用项目内路径读取,该路径只在开发工具中显示,所以只能在开发工具中使用,项目部署之后无法读取。(不通用)
@SpringBootTest
public class ResourcesFIleTest {
@Test
void test01() {
System.out.println(new File("src/main/resources/static/image/001.png").exists());
}
}
3、方式二:org.springframework.util.ResourceUtils
使用 org.springframework.util.ResourceUtils 读取,在 Linux 环境中无法读取。(不通用)
@SpringBootTest
public class ResourcesFIleTest {
@Test
void test02() throws FileNotFoundException {
System.out.println(ResourceUtils.getFile("classpath:static/image/001.png").exists());
}
}
4、方式三:org.springframework.core.io.ClassPathResource
使用 org.springframework.core.io.ClassPathResource,各环境都能读取。(通用)
@SpringBootTest
public class ResourcesFIleTest {
@Test
void test03() throws IOException {
System.out.println(new ClassPathResource("static/image/001.png").getFile().exists());
}
}
5、方式四:org.springframework.core.io.ResourceLoader
结合 Spring 注解,使用 org.springframework.core.io.ResourceLoader。(通用)
@SpringBootTest
public class ResourcesFIleTest {
@Autowired
ResourceLoader resourceLoader;
@Test
void test04() {
System.out.println(resourceLoader.getResource("classpath:static/image/001.png").exists());
}
}