一、Spring Boot默認靜態文件路徑
在Spring Boot中,我們可以通過靜態資源文件夾來存放我們的網頁、圖片等資源,其中默認的靜態資源文件夾是 “/src/main/resources/static”。例如我們將一個名為 index.html 的網頁文件放在該目錄下,那我們可以通過 URL:localhost:8080/index.html 來訪問該網頁。
值得注意的是,如果我們不想使用默認路徑,也可以通過application.properties文件重新指定靜態資源文件夾的路徑:
spring.resources.static-locations=classpath:/static/,file:/opt/files/
上述代碼定義了靜態資源文件夾的搜索位置,優先搜索項目的 “classpath:/static/” 路徑,若未找到則搜索文件系統下的 “/opt/files/” 路徑。
二、Spring Boot項目獲取文件路徑
在實際開發中,我們也常常需要獲取項目中某個文件或目錄的絕對路徑,Spring Boot提供了多種方式來實現。以下是其中幾種比較常見的方式:
1)利用ClassPathResource獲取資源文件
通過ClassPathResource獲取資源文件,可以獲取存放在 “classpath:” 路徑下的文件。下面是一個簡單示例:
ClassPathResource resource = new ClassPathResource("config.properties"); String path = resource.getFile().getAbsolutePath();
上述代碼實現了獲取 “classpath:” 下的 “config.properties” 文件的絕對路徑。
2)利用ServletContext獲取資源文件
通過ServletContext獲取資源文件,一般用於獲取存放在web應用程序相對路徑下的文件。下面是一個簡單示例:
InputStream inputStream = request.getServletContext().getResourceAsStream("/WEB-INF/classes/file.txt"); String path = request.getServletContext().getRealPath("/WEB-INF/classes/file.txt");
上述代碼實現了獲取 “webapp/WEB-INF/classes/file.txt” 文件的流和絕對路徑。
3)利用ResourceLoader獲取資源文件
ResourceLoader是一個高級的Spring特性,用於獲取項目路徑下的資源文件。下面是一個使用ResourceLoader獲取yml配置文件的例子:
@Autowired private ResourceLoader resourceLoader; private String getConfig(String fileName) { Resource resource = resourceLoader.getResource("classpath:" + fileName); try { InputStream inputStream = resource.getInputStream(); byte[] b = new byte[inputStream.available()]; inputStream.read(b); return new String(b); } catch (IOException e) { e.printStackTrace(); } return null; }
上述代碼實現了通過ResourceLoader獲取 “classpath:” 下的yml配置文件。
三、小結
本文介紹了Spring Boot中獲取文件路徑的多種方式,包括獲取靜態文件路徑和項目中一個文件或目錄的絕對路徑。通過這些方式,我們可以輕鬆地獲取到所需文件的路徑,從而實現對文件進行讀取、寫入等操作。
原創文章,作者:CWPTN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/361803.html