335
791
管理员
可以使用类加载器来获取资源文件的输入流。该方法接受一个资源文件路径参数,返回一个 InputStream 对象。
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xiaozi.txt");
该方法返回的资源文件路径是相对于类加载器的根路径。即程序编译后的classes文件夹所在目录,如需要加载其他目录中,需要在前面添加目录结构(如:static/xiaozi.txt)。注:static前面不能添加“/”。
InputStream inputStream = this.getClass().getResourceAsStream("/xiaozi.txt");
@Autowired private ResourceLoader resourceLoader; Resource resource = resourceLoader.getResource("classpath:xiaozi.txt");
File file = ResourceUtils.getFile("classpath:xiaozi.txt");
@Autowired private ApplicationContext applicationContext; Resource resource = applicationContext.getResource("classpath:xiaozi.txt");
File file = new File("src/main/resources/xiaozi.txt");
Path path = Paths.get("src/main/resources/xiaozi.txt"); InputStream inputStream = Files.newInputStream(path);
ClassPathResource resource = new ClassPathResource("xiaozi.txt");
ClassLoader.getResourceAsStream() :这是一种通用的方式,可以适用于大多数情况。
ResourceLoader :Spring 框架中,可以使用 ResourceLoader 接口来加载资源文件。这种方式适用于大多数 Spring Boot 项目。
ClassPathResource:如果只需要读取 resources 目录下的文件,可以使用。这种方式较为简单。
举报
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
|手机版|小黑屋|依星源码资源网-分享编程干货的网站 ( 鲁ICP备2021043233号-3 )
GMT+8, 2023-10-2 00:23
邮箱:312337667@qq.com 客服QQ:312337667(工作时间:7:00~23:00)
© Powered by Net188.com X3.4