Spring 進階(9)訪問資源(1)
阿新 • • 發佈:2018-12-10
- Spring提供了一個很膩害的資源訪問介面--Resource,注意,是提供了一個介面,而不是提供了一個類,實際上它提供了好多好多類,這種面向介面程式設計的思想是很酷的~~~~
- 閒話少敘,說第一個Resource介面的實現類--UrlResource,這個類通過在構造方法中傳入需要獲取的資源的訪問協議加上檔案來訪問。看代程式碼碼吧
- 這個例子又有坑,又沒有包,SAXReader需要dom4包的支援,這是連結。導包都會了把~~
<?xml version="1.0" encoding="GBK" ?> <a> <b> <c>this is the first</c> <c>this is the second</c> </b> </a>
package url_resoure; import org.springframework.core.io.UrlResource; import org.dom4j.*; import org.dom4j.io.*; import java.util.*; public class UrlResourceTest { public static void main(String []args) throws Exception{ UrlResource urlResource = new UrlResource("file:test.xml"); // 在例項化UrlResource物件的時候把資源的訪問協議和檔案路徑檔名傳進去 // 輸出檔案的相關資訊 System.out.println(urlResource.getDescription()); System.out.println(urlResource.getFilename()); SAXReader saxReader = new SAXReader(); // 構建 SAXReader解析器來解析那個檔案 // 接下來的操作就是兩層遍歷,然後輸出來 Document document = saxReader.read(urlResource.getFile()); Element element = document.getRootElement(); List list = element.elements(); for(Iterator iterator = list.iterator(); iterator.hasNext(); ){ Element element1 = (Element)iterator.next(); List list1 = element1.elements(); for(Iterator iterator1 = list1.iterator(); iterator1.hasNext(); ){ Element element2 = (Element)iterator1.next(); System.out.println(element2.getText()); } } } } //執行程式,看到下面的輸出 // this is the first // this is the second
這是我看李剛編著的《輕量級javaEE企業應用實戰(第五版)-Struts2+Spring5+Hibernate5/JAP2》後總結出來的。