2012-03-04 51 views
1

我發現自己處於一個兩難的境地,找到一種方法來檢索urlpath。 我想從一個HTTP URL檢索基本網址,例如:找到http URL路徑的困境

http://www.test.com/somepath/path1/ 
base url is : test.com/somepath/path1 

http://www.test.com/somepath/path1/file1.html 
base url is : test.com/somepath/path1 

http://www.test.com/somepath/path1/path2 
base url is : test.com/somepath/path1/path2 

但在使用URL對象,並使用和getHost()和的getPath()和的GetFile()的Java我會得到下面的結果:

1. 
host : www.test.com (correct) 
path : /somepath/path1 (correct) 
file : /somepath/path1 (it should be empty but its not!) 
2. 
host : www.test.com (correct) 
path : /somepath/path1/file1.html (incorrect) 
file : /somepath/path1/file1.html (it should be file1.html) 
3. 
host : www.test.com (correct) 
path : /somepath/path1/path2 (correct) 
file : /somepath/path1/path2 (it should be empty/null) 

我該如何克服這個問題?

+0

那麼你有什麼嘗試? – 2012-03-04 01:09:01

+0

正如我解釋:URL.getHost()/ getPath()/ getFile() – 2012-03-04 01:13:25

+0

你可以添加代碼的問題?當我們看到代碼時,更容易看到問題所在。 – 2012-03-04 01:19:32

回答

3

url對象不知道/ path2是一個文件還是一個目錄,因爲如果url沒有以「/」結尾,它就不是一個目錄。您可以添加額外的支票來解決這個問題。拆分url並檢查最後一部分是否包含「。」例如在「index.html」中找到。

代碼示例

String[] urlSplt = urlStr.split("/"); 
if(urlSplt[urlSplt.length - 1].contains(".")){ 
    //URL is a file 
} else{ 
    //url is not a file 
} 

祝你好運!