[英]URL parse without String split
Java有很酷的URL解析器
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("path = " + aURL.getPath());
}
}
這是程序顯示的輸出:
path = /docs/books/tutorial/index.html
我只想參加這一部分: docs/books/tutorial
(或/docs/books/tutorial/
)猜測不要使用字符串拆分,我正在尋找其他更好的解決方案來完成此任務。
先感謝您
String path = "/docs/books/tutorial/index.html";
path = path.substring(1, path.lastIndexOf("/"));
提供docs/books/tutorial
您可以使用文件對象來執行此操作,而不是拆分字符串:
工作示例:
import java.io.File;
import java.net.URL;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("path = " + aURL.getPath());
File file = new File(aURL.getPath());
System.out.println("pathOnly = " + file.getParent());
}
}
輸出:
path = /docs/books/tutorial/index.html
pathOnly = /docs/books/tutorial
有幾種方法。 其中之一是使用URI#resolve(".")
其中.
代表當前目錄 。 因此您的代碼如下所示:
URI uri = new URI("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println(uri.resolve(".").getPath());
輸出: /docs/books/tutorial/
其他方法可能涉及處理文件系統的文件系統和類,例如File
或Java 7 Path
引入的改進版本(及其實用程序類Paths
)。
這些類應允許您解析path
/docs/books/tutorial/index.html
並獲取其父位置/docs/books/tutorial
。
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
String path = aURL.getPath();
String parent = Paths.get(path).getParent().toString();
System.out.println(parent);// \docs\books\tutorial
(警告:根據您的操作系統,您可能會使用\\
而不是/
來分隔路徑)
以此為例:
public static String getCustomPath() {
String path = "/docs/books/tutorial/index.html";
String customPath = path.substring(0, path.indexOf("index.html"));
return customPath;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.