【问题标题】:Java: String manipulation. Fetch last subpath in a URLJava:字符串操作。获取 URL 中的最后一个子路径
【发布时间】:2023-03-22 18:53:01
【问题描述】:

假设我有一个 URL http://example.com/files/public_files/test.zip,我想提取最后一个子路径,所以 test.zip,我该怎么做?

我来自 Python,所以我对 Java 和学习仍然很陌生。在 Python 中,你可以这样做:

>>> x = "http://example.com/files/public_files/test.zip"
>>> x.split("/")[-1]
'test.zip'

【问题讨论】:

标签: java string split substring


【解决方案1】:

有很多方法。我更喜欢:

String url = "http://example.com/files/public_files/test.zip";
String fileName = url.substring(url.lastIndexOf("/") + 1);

【讨论】:

    【解决方案2】:

    使用 String 类方法是一种方法。但鉴于你有一个 URL,你可以使用java.net.URL.getFile():

    String url = "http://example.com/files/public_files/test.zip";
    String filePart = new URL(url).getFile();
    

    上面的代码将为您提供完整的路径。要获取文件名,可以使用Apache Commons - FilenameUtils.getName()

    String url = "http://example.com/files/public_files/test.zip";
    String fileName = FilenameUtils.getName(url);
    

    好吧,如果您不想为此任务引用 3rd 方库,String 类仍然是一个选择。我刚刚给出了另一种方式。

    【讨论】:

    • 你必须处理MalformedURLException,这实际上返回/files/public_files/test.zip
    • @jlordo。太糟糕了。没有获取文件名的方法。 :(
    • @jlordo。在 Apache Commons 中找到了一个。 :)
    【解决方案3】:

    您可以使用以下内容:

    String url = "http://example.com/files/public_files/test.zip";
    String arr[] = url.split("/");
    String name = arr[arr.length - 1];
    

    【讨论】:

      【解决方案4】:

      最类似于python的语法是:

      String url = "http://example.com/files/public_files/test.zip";
      String [] tokens = url.split("/");
      String file = tokens[tokens.length-1];
      

      Java 缺少 Python 所具有的方便的 [-n] nth to last 选择器。如果您想在一行中完成所有操作,则必须执行以下粗暴的操作:

      String file = url.split("/")[url.split("/").length-1];
      

      我不推荐后者

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-19
        • 2019-07-24
        • 1970-01-01
        • 2015-01-17
        • 2022-01-09
        • 1970-01-01
        • 2020-04-13
        • 1970-01-01
        相关资源
        最近更新 更多