java URL相對路徑轉換成絕對路徑

原文鏈接: https://www.iteye.com/blog/jsczxy2-1683516

//絕對路徑  
String absolutePath = "http://www.aaa.com/1/2/3.html";  
//相對路徑  
String relativePath = "../../a.jpg";  
  
//以下方法對相對路徑進行轉換  
URL absoluteUrl = new URL(absolutePath);  
  
URL parseUrl = new URL(absoluteUrl ,relativePath );  
  
//最終結果  
log.info("相對路徑轉換後的絕對路徑:" + parseUrl .toString());   

展示了一些例子: 

public void test1() {
	//絕對路徑  
	String absolutePath = "http://www.aaa.com/1/2/3.html";  
	//相對路徑  
	String relativePath = "../../a.jpg";  //http://www.aaa.com/a.jpg
	//但是設置往上3層時,即"../../../a.jpg",輸出了http://www.aaa.com/../a.jpg
	//relativePath = "a.jpg";
		//http://www.aaa.com/1/2/a.jpg
	//relativePath = "3/4/5.jpg";
		//http://www.aaa.com/1/2/3/4/5.jpg
	//relativePath = "https://www.baidu.com";
		//輸出:https://www.baidu.com
	//以下方法對相對路徑進行轉換  
	URL absoluteUrl = null;
	try {
		absoluteUrl = new URL(absolutePath);
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		System.out.println("參考的絕對地址格式不正確");
		e.printStackTrace();
	}  
	  
	URL parseUrl = null;
	try {
		parseUrl = new URL(absoluteUrl ,relativePath );
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}    
	//最終結果  
	System.out.println("相對路徑轉換後的絕對路徑:" + parseUrl .toString());
}
  • 比較方便的是,可以識別“../../c.jpg”類似的相對路徑
  • 如果輸入的相對路徑是合法的完整路徑,則直接返回該路徑
  • 如果絕對路徑本身不是合法的,則拋出異常,可自行添加處理的代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章