這篇文章給大家介紹Spring中的工具類有哪些,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
文件資源操作
Spring 定義了一個 org.springframework.core.io.Resource 接口,Resource 接口是為了統一各種類型不同的資源而定義的,Spring 提供了若干 Resource 接口的實現類,這些實現類可以輕松地加載不同類型的底層資源,并提供了獲取文件名、URL 地址以及資源內容的操作方法
訪問文件資源
* 通過 FileSystemResource 以文件系統絕對路徑的方式進行訪問;
* 通過 ClassPathResource 以類路徑的方式進行訪問;
* 通過 ServletContextResource 以相對于 Web 應用根目錄的方式進行訪問。
package com.baobaotao.io; import java.io.IOException; import java.io.InputStream; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; public class FileSourceExample { public static void main(String[] args) { try { String filePath = "D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt"; // ① 使用系統文件路徑方式加載文件 Resource res1 = new FileSystemResource(filePath); // ② 使用類路徑方式加載文件 Resource res2 = new ClassPathResource("conf/file1.txt"); InputStream ins1 = res1.getInputStream(); InputStream ins2 = res2.getInputStream(); System.out.println("res1:"+res1.getFilename()); System.out.println("res2:"+res2.getFilename()); } catch (IOException e) { e.printStackTrace(); } } }