[英]URL parse without String split
Java has cool URL parser 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());
}
}
Here is the output displayed by the program: 这是程序显示的输出:
path = /docs/books/tutorial/index.html
I would like to take only this part : docs/books/tutorial
(or /docs/books/tutorial/
) Guessing don`t use string split, I am looking for other better resolution for this task. 我只想参加这一部分:
docs/books/tutorial
(或/docs/books/tutorial/
)猜测不要使用字符串拆分,我正在寻找其他更好的解决方案来完成此任务。
Thank you in advance 先感谢您
String path = "/docs/books/tutorial/index.html";
path = path.substring(1, path.lastIndexOf("/"));
gives docs/books/tutorial
提供
docs/books/tutorial
You can do it with a File Object, rather than split your String: 您可以使用文件对象来执行此操作,而不是拆分字符串:
Working example: 工作示例:
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());
}
}
Output: 输出:
path = /docs/books/tutorial/index.html
pathOnly = /docs/books/tutorial
There are few ways. 有几种方法。 One of them is using
URI#resolve(".")
where .
其中之一是使用
URI#resolve(".")
其中.
represents current directory . 代表当前目录 。 So your code can look like:
因此您的代码如下所示:
URI uri = new URI("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println(uri.resolve(".").getPath());
Output: /docs/books/tutorial/
输出:
/docs/books/tutorial/
Other way could involve file system and classes which handle it like File
or its improved version introduced in Java 7 Path
(and its utility class Paths
). 其他方法可能涉及处理文件系统的文件系统和类,例如
File
或Java 7 Path
引入的改进版本(及其实用程序类Paths
)。
These classes should allow you to parse path
这些类应允许您解析
path
/docs/books/tutorial/index.html
and get its parent location /docs/books/tutorial
. 并获取其父位置
/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
(little warning: depending on your OS you may get path separated with \\
instead of /
) (警告:根据您的操作系统,您可能会使用
\\
而不是/
来分隔路径)
Take this as a example: 以此为例:
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.