2012-04-15 14 views

उत्तर

20

कोड मैं के बारे में सोच सकता है की सबसे छोटा टुकड़ा यह है :

private String getParent(String resourcePath) { 
    int index = resourcePath.lastIndexOf('/'); 
    if (index > 0) { 
     return resourcePath.substring(0, index); 
    } 
    return "/"; 
} 

मैं साधारण समारोह बनाया है, मैंके कोड से प्रेरित था:

URI uri = new URI("http://www.stackoverflow.com/path/to/something"); 

URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".") 
+1

URI.resolve अधिक जटिल परिचालनों के लिए भी बहुत अच्छा है ... जैसे uri.resolve ("dir/file.txt") – David

+0

यह प्रोटोकॉल "jar: file: ..." के साथ यूआरआई के लिए काम नहीं करता है, जो संसाधनों के साथ होता है जो जेएआर फाइलों में स्थित हैं। –

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

विंडोज़ पर यह वापस स्लेश प्रस्तुत करता है। – Sogartar

0

यहाँ बहुत ही सरल समाधान जो अपने प्रयोग के मामले में सबसे अच्छा तरीका थामेरे कोड में विंडोज़ पर बैक स्लेश के साथ कोई समस्या नहीं है। मुझे लगता है कि resourcePath प्रोटोकॉल, डोमेन और पोर्ट नंबर के बिना यूआरएल का संसाधन हिस्सा है। (उदाहरण के लिए /articles/sport/atricle_nr_1234)

संबंधित मुद्दे