繁体   English   中英

如何从URL的最后一个路径中拆分其余URL

[英]How do I split the rest of the URL from the last path of it

我有此文件URL: http://xxx.xxx.xx.xx/resources/upload/2014/09/02/new sample.pdf ,它将转换为http://xxx.xxx.xx.xx/resources/upload/2014/09/02/new%20sample.pdf稍后http://xxx.xxx.xx.xx/resources/upload/2014/09/02/new%20sample.pdf

现在,我可以通过以下方式获得最后的路径:

public static String getLastPathFromUrl(String url) {
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

这将给我new sample.pdf

但是如何获取其余的URL: http://xxx.xxx.xx.xx/resources/upload/2014/09/02/

从URL获取最后路径的更简单方法是使用String.split函数,如下所示:

String url = "http://xxx.xxx.xx.xx/resources/upload/2014/09/02/new sample.pdf";
String[] urlArray = url.split("/");
String lastPath = urlArray[urlArray.length-1];

这会将您的网址转换为数组,然后可以以多种方式使用它。 有多种获取url-lastPath的方法,一种方法是使用答案加入上面生成的Array。 或像这样使用lastIndexOf()和子字符串:-

String restOfUrl = url.substring(0,url.lastIndexOf("/"));

PS:-尽管您可以通过这样做来学到一些东西,但是我认为您最好的解决方案是用完整的URL字符串中的%20替换空格,这将是最快的,更有意义。

我不确定我是否理解正确,但是当您说

我有以下文件URL:URL / new sample.pdf ,稍后将转换为URL / new%20sample.pdf

似乎您正在尝试用URL中的%20替换“空格”,或者用简单的话说来尝试处理URL中不需要的字符。 如果那是您需要的,请使用预制的

URLEncoder.encode(String url,String enc),您可以将ÜTF-8用作编码。

http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html

如果您确实需要拆分它,那么假设您对http://之后的URL感兴趣,请删除http://,然后将剩余的URL存储在称为say剩余URL的字符串变量中。 然后使用

列表myList = new ArrayList(Arrays.asList(remainingURL.split(“ /”))));

您可以迭代myList以获得其余的URL片段。

我发现了:

    File file=new File("http://xxx.xxx.xx.xx/resources/upload/2014/09/02/new sample.pdf");
    System.out.println(file.getPath().replaceAll(file.getName(),""));

输出: http://xxx.xxx.xx.xx/resources/upload/2014/09/02/

弹簧解决方案:

List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String lastPath = pathSegments.get(pathSegments.size()-1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM