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);