risc-v中文社区

 找回密码
 立即注册
查看: 946|回复: 1

[原创] classpath下的资源读取

[复制链接]

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
发表于 2022-5-12 10:52:01 | 显示全部楼层 |阅读模式
很简单的一个问题,记录一下:springboot 2.x,IDEA开发环境下,在resources目录中有一个png图片需要读取。

1)
FileInputStream input= null;
try {
    input = new FileInputStream(ResourceUtils.getFile("classpath:static/inout.png"));
    Image image =new Image(input);
    imgView=new ImageView(image);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
在IDEA中调试一切OK,但做成jar之后执行则出现FileNotFoundException异常。换成如下代码:
2)
InputStream input= null;
ClassPathResource classPathResource = new ClassPathResource("/static/inout.png");
try {
    input = classPathResource.getInputStream();
    Image image =new Image(input);
    imgView=new ImageView(image);
}
catch (IOException e){
    e.printStackTrace();
}
则在IDEA中调试和生成JAR之后单独执行都OK。

回复

使用道具 举报

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
 楼主| 发表于 2022-5-12 10:52:22 | 显示全部楼层
其实类似2)这样的代码还有二种:
3)
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/static/inout.png");
4)
InputStream inputStream = this.getClass().getResourceAsStream("/static/inout.png");
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-5-4 00:39 , Processed in 0.014245 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表