【问题标题】:How to get parent URL in Java?如何在 Java 中获取父 URL?
【发布时间】:2022-04-18 02:24:01
【问题描述】:

在 Objective-C 中,我使用 -[NSURL URLByDeletingLastPathComponent] 来获取父 URL。这在 Java 中相当于什么?

【问题讨论】:

    标签: java url


    【解决方案1】:

    我能想到的最短的 sn-p 代码是这样的:

    URI uri = new URI("http://www.stackoverflow.com/path/to/something");
    
    URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
    

    【讨论】:

    • URI.resolve 也适用于更复杂的操作...比如 uri.resolve("dir/file.txt")
    • 这似乎不适用于协议为“jar:file:...”的 URI,这种情况发生在 JAR 文件中的资源中。
    【解决方案2】:

    我不知道库函数可以一步完成。但是,我相信以下(诚然繁琐)代码可以完成您所追求的(并且您可以将其包装在您自己的实用程序函数中):

    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 );
        }
    }
    

    【讨论】:

    • 在 Windows 上,这会引入反斜杠。
    【解决方案3】:

    这是一个非常简单的解决方案,这是我用例中最好的方法:

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

    我创建了一个简单的函数,我受到File::getParent 代码的启发。在我的代码中,Windows 上的反斜杠没有问题。我假设resourcePath 是 URL 的资源部分,没有协议、域和端口号。 (例如/articles/sport/atricle_nr_1234

    【讨论】:

      【解决方案4】:

      Guava 库提供的简单解决方案。

      代码:

      URL url = new URL("https://www.ibm.watson.co.uk");
      String host = url.getHost();
      
      InternetDomainName parent = InternetDomainName.from(host).parent(); // returns ibm.watson.co.uk
      System.out.println("Immediate ancestor: "+parent);
      
      
      ImmutableList<String> parts = InternetDomainName.from(host).parts(); 
      System.out.println("Individual components:  "+parts);
      
      
      InternetDomainName name = InternetDomainName.from(host).topPrivateDomain(); // watson.co.uk
      System.out.println("Top private domain - " + name);
      

      输出:

      Immediate ancestor: ibm.watson.co.uk
      
      Individual components:  [www, ibm, watson, co, uk]
      
      Top private domain - watson.co.uk
      

      供参考: https://guava.dev/releases/snapshot/api/docs/com/google/common/net/InternetDomainName.html

      需要依赖:

      https://mvnrepository.com/artifact/com.google.guava/guava

      我使用的是 19.0 版

      <dependency>
              <groupId>com.google.guava</groupId>
              <artifactId>guava</artifactId>
      </dependency>
      

      而且,这个类 InternetDomainName 提供了更多相关功能。

      【讨论】:

        【解决方案5】:

        更简洁的方式

        import java.nio.file.Paths;
        URI child=....;
        URI parent=Paths.get(child).getParent().toUri();
        

        就是这样..

        【讨论】:

          【解决方案6】:

          使用 java.nio.file.Paths 可以在一行中完成。

          例如:

          String parent = Paths.get("https://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java/").getParent().toString();
          System.out.println(parent);
          

          将打印:

          https:/stackoverflow.com/questions/10159186
          

          请记住 https:/ 缺少斜杠,因此您可以将其添加到另一个替换中:

          String parent = Paths.get("https://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java/").getParent().toString().replace("https:/","https://");
          
          System.out.println(parent);
          

          将打印:

          https://stackoverflow.com/questions/10159186
          

          【讨论】:

            猜你喜欢
            • 2018-11-15
            • 2020-06-29
            • 2017-06-18
            • 2011-04-13
            • 2016-09-15
            • 2011-04-08
            • 1970-01-01
            • 2017-11-13
            • 1970-01-01
            相关资源
            最近更新 更多