在Objective-C中,我使用-[NSURL URLByDeletingLastPathComponent]
來獲取父URL。在Java中相當於什麼?如何在Java中獲取父URL?
7
A
回答
20
最短的代碼,我能想到的片段是這樣的:
URI uri = new URI("http://www.stackoverflow.com/path/to/something");
URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".")
3
我不知道庫函數在一個步驟中做到這一點。然而,代碼我相信下面的(當然繁瑣)位完成後,你在做什麼(你可以在自己的效用函數包裝這件事):
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest
{
public static void main(String[] args) throws MalformedURLException
{
// make a test url
URL url = new URL("http://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java");
// represent the path portion of the URL as a file
File file = new File(url.getPath());
// get the parent of the file
String parentPath = file.getParent();
// construct a new url with the parent path
URL parentUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), parentPath);
System.out.println("Child: " + url);
System.out.println("Parent: " + parentUrl);
}
}
+2
在Windows上,這引入了反斜槓。 – Sogartar 2013-01-18 12:56:39
0
這是非常簡單的解決方案,它是在我使用的情況下,最好的辦法:
private String getParent(String resourcePath) {
int index = resourcePath.lastIndexOf('/');
if (index > 0) {
return resourcePath.substring(0, index);
}
return "/";
}
我創建了簡單的功能,我被代碼啓發3210。在我的代碼中,Windows上的反斜槓沒有問題。我認爲resourcePath
是URL的資源部分,沒有協議,域和端口號。 (例如/articles/sport/atricle_nr_1234
)
相關問題
- 1. 獲取證書父項的URL(JAVA)
- 2. 如何從firebase中獲取父值java
- 3. 如何從html塊中的php iFrame獲取父url url
- 4. 如何在C中獲取父URL引用者#
- 5. 如何在java中獲取Elasticsearch中的文檔的父ID?
- 6. 如何在java中獲得父面板?
- 7. Java:如何在涉及父/子時獲取ArrayList中的值?
- 8. 從iframe中獲取父url變量
- 9. 如何驗證Java以獲取URL
- 10. 如何獲取Java Servlet的正確URL?
- 11. 如何使用java從給定的url中獲取基址url
- 12. 如何從java中的相對url獲取絕對url
- 13. JAVA獲取URL API
- 14. 如何從ASP.NET中的iframe獲取父級的URL
- 15. 如何獲取IE11中iframe的父站點的URL?
- 16. #在java中獲取url參數
- 17. 如何使用Remember The Milk API在Java中獲取URL?
- 18. 如何在Java中動態獲取URL參數?
- 19. 如何在java中使用代理獲取URL連接?
- 20. 如何在PHP中獲取URL
- 21. 如何在Rails中獲取URL參數?
- 22. 如何在Wordpress中獲取URL?
- 23. Appium:如何在webview中獲取URL
- 24. 如何在outSequence中獲取URL?
- 25. 如何在模板中獲取ImageField URL?
- 26. 如何在Symfony2中解析獲取url?
- 27. 如何在jsp中獲取基礎url?
- 28. 如何在jquery mobile中獲取url?
- 29. 如何在Django中獲取url變量?
- 30. 如何在cakephp中獲取url參數?
對於更復雜的操作,URI.resolve也很棒......就像uri.resolve(「dir/file.txt」) – David 2013-10-20 19:25:51
這對於協議爲「jar:file:...」的URI似乎不起作用,它與位於JAR文件中的資源一起發生。 – 2016-10-01 19:52:48