簡體   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