spring boot读取resources下面的文件图片
下面的代码是为了保证在打成jar包的情况下依然能够有效读取到文件。
先看项目目录结构:
我是想读取resources下面的图片,下面放上代码:
Random random = new Random();
int num = random.nextInt(picNum)+1;
ClassPathResource classPathResource = new ClassPathResource("/static/code/"+num+".jpg");
InputStream inputStreamImg = classPathResource.getInputStream();
Image img = ImageIO.read(inputStreamImg);
我先写了个随机数,随机取到1-6的图片,根据输入流来获取,这个根据个人情况而定,注意一点的是,spring boot的resources目录,我们在new ClassPathResource()中,只需要写resources下面的路径就好,如果是读取文件不是图片,用下面的代码,整体问题不大
File file = classPathResource.getFile();
当然我们也可以用ResourceUtils来读取文件,不过具有局限性,这里也顺便粘上:
picPath = ResourceUtils.getURL("classpath:").getPath()+"static/code/";
Random random = new Random();
int num = random.nextInt(picNum)+1;
String path = picPath+num+".jpg";
File file = new File(path);
Image img = ImageIO.read(file);